/* ============================================================
   Tech glossary — a plain-English popup of the words people
   nod along to but never get explained. Modeled on the
   keyboard cheat-sheet modal. Used on technologies.html.
   ============================================================ */

const GLOSSARY_TERMS = [
  // Foundations
  { term: "Frontend", cat: "Foundations", def: "Everything you see and tap — the screens, buttons and layouts. It runs on your phone or in your browser." },
  { term: "Backend", cat: "Foundations", def: "The part you never see: the servers, logic and databases that do the work after you tap. The kitchen behind the restaurant." },
  { term: "Full-stack", cat: "Foundations", def: "Work that spans both frontend and backend — and an engineer comfortable across the whole thing." },
  { term: "Server", cat: "Foundations", def: "A computer, always on somewhere, whose job is to answer requests from apps and browsers." },
  { term: "Database", cat: "Foundations", def: "Where an app stores its information so it's still there next time — users, orders, messages, all of it." },
  { term: "Cloud", cat: "Foundations", def: "Renting computers and storage from a big provider instead of owning the hardware. 'The cloud' is just someone else's data center." },

  // The web
  { term: "API", cat: "How things talk", def: "A defined way for two pieces of software to talk. Like a waiter: you ask for something specific, it brings it back — you never see the kitchen." },
  { term: "Endpoint", cat: "How things talk", def: "One specific address on an API you can call — e.g. 'give me this user's orders.'" },
  { term: "CRUD", cat: "How things talk", def: "Create, Read, Update, Delete — the four basic things almost every app does to its data. Add a note, view it, edit it, delete it." },
  { term: "JSON", cat: "How things talk", def: "A simple, readable text format apps use to send data to each other. Most APIs speak it." },
  { term: "Webhook", cat: "How things talk", def: "A reverse API call — instead of you asking, a service pings you the moment something happens ('a payment just arrived')." },
  { term: "HTTPS / SSL", cat: "How things talk", def: "The padlock in your browser. It encrypts the connection so no one in between can read what's sent." },

  // Building
  { term: "Framework", cat: "Building blocks", def: "A pre-built foundation that handles the repetitive parts so engineers build features, not plumbing. Next.js and Flutter are frameworks." },
  { term: "Library", cat: "Building blocks", def: "A reusable bundle of code you drop in to do one job — a date picker, a chart — without writing it yourself." },
  { term: "SDK", cat: "Building blocks", def: "Software Development Kit — a toolbox a company gives you to plug their service (payments, maps) into your app." },
  { term: "Open source", cat: "Building blocks", def: "Code anyone can read, use and improve for free. Much of the internet runs on it." },
  { term: "Repository (repo)", cat: "Building blocks", def: "The folder where a project's code lives and its full history is tracked. Usually on GitHub." },
  { term: "Git", cat: "Building blocks", def: "The system that tracks every change to code, so teams can work together and undo mistakes safely." },

  // Apps
  { term: "Native app", cat: "Kinds of apps", def: "An app built specifically for iOS or Android, installed from the App Store. Fastest, deepest access to the phone." },
  { term: "Cross-platform", cat: "Kinds of apps", def: "Writing the app once and running it on both iOS and Android — saving time and budget." },
  { term: "Web app", cat: "Kinds of apps", def: "An app that runs in the browser, nothing to install. Gmail is a web app." },
  { term: "PWA", cat: "Kinds of apps", def: "Progressive Web App — a website that can be installed and works offline, blurring the line with native apps." },
  { term: "UI", cat: "Kinds of apps", def: "User Interface — the visual design: what the product looks like." },
  { term: "UX", cat: "Kinds of apps", def: "User Experience — how the product feels to use: is it clear, fast, frustrating, delightful?" },

  // Shipping
  { term: "Deployment", cat: "Shipping & ops", def: "Putting code live so real people can use it. 'We deployed the fix' = it's now in your hands." },
  { term: "Hosting", cat: "Shipping & ops", def: "Where an app actually runs and is served from — the always-on home for its code and files." },
  { term: "CI/CD", cat: "Shipping & ops", def: "Automation that tests code and ships it safely every time it changes — so releases are routine, not scary." },
  { term: "Cache", cat: "Shipping & ops", def: "A temporary copy kept close by so things load instantly instead of being fetched again. Why a page is faster the second time." },
  { term: "Latency", cat: "Shipping & ops", def: "The delay between asking for something and getting it. Low latency feels instant; high latency feels laggy." },
  { term: "Bug", cat: "Shipping & ops", def: "A mistake in the code that makes the software behave wrong. Fixing them is most of engineering." },

  // Smarts
  { term: "Algorithm", cat: "Data & AI", def: "A precise set of steps to solve a problem — like a recipe a computer follows exactly." },
  { term: "Machine learning", cat: "Data & AI", def: "Software that finds patterns in examples instead of being told every rule — the basis of modern AI." },
  { term: "LLM", cat: "Data & AI", def: "Large Language Model — the kind of AI behind chat assistants. It predicts text well enough to answer, summarize and write code." },
  { term: "Token", cat: "Data & AI", def: "The small chunks of text an AI reads and writes in. Roughly ¾ of a word each — and what AI usage is billed by." },
  { term: "Authentication", cat: "Data & AI", def: "Proving who you are — logging in. (Authorization is the next step: what you're allowed to do.)" },
  { term: "RTL", cat: "Data & AI", def: "Right-to-Left — designing interfaces to read correctly in Arabic and other RTL languages, not just mirrored English." },

  // How things talk (more)
  { term: "REST", cat: "How things talk", def: "The most common style of API — predictable web addresses for your data, using plain web verbs to get, add, change or remove it." },
  { term: "Request / Response", cat: "How things talk", def: "The basic exchange of the web: your app sends a request, the server sends a response back. Every tap is a tiny conversation." },

  // Building blocks (more)
  { term: "Source code", cat: "Building blocks", def: "The human-readable instructions engineers write. It gets run or compiled to become the working app." },
  { term: "Version control", cat: "Building blocks", def: "Keeping a full, rewindable history of every change to the code, so nothing is ever truly lost. Git is the standard." },
  { term: "Pull request (PR)", cat: "Building blocks", def: "A proposed change to the code, opened for teammates to review before it joins the main project." },
  { term: "Environment", cat: "Building blocks", def: "A separate copy of the app for a purpose — 'development' to build in, 'staging' to test, 'production' for real users." },

  // Quality & reach
  { term: "Responsive design", cat: "Quality & reach", def: "Layouts that adapt to any screen — phone, tablet, desktop — instead of breaking on the small ones." },
  { term: "Accessibility (a11y)", cat: "Quality & reach", def: "Designing so everyone can use the product — keyboard, screen reader, low vision, reduced motion. A requirement, not an extra." },
  { term: "SEO", cat: "Quality & reach", def: "Search Engine Optimization — building a site so Google understands and ranks it, bringing visitors without paid ads." },
  { term: "Performance budget", cat: "Quality & reach", def: "A hard limit on how heavy a page is allowed to be, so it stays fast on cheap phones and slow networks." },

  // Security & data
  { term: "Authorization", cat: "Security & data", def: "What you're allowed to do once logged in — an admin sees more than a guest. The step after authentication." },
  { term: "Encryption", cat: "Security & data", def: "Scrambling data so only the right key can read it — protecting it both in transit and at rest." },
  { term: "GDPR", cat: "Security & data", def: "The EU's data-protection law: rules for handling personal data — consent, access, deletion — with real penalties for getting it wrong." },

  // Data & AI (more)
  { term: "Prompt", cat: "Data & AI", def: "The instruction you give an AI model. Clear, specific prompts get better results — writing them well is its own craft." },
  { term: "RAG", cat: "Data & AI", def: "Retrieval-Augmented Generation — giving an AI your own documents to answer from, so it cites real facts instead of guessing." },
  { term: "Inference", cat: "Data & AI", def: "Actually running a trained AI model to get an answer. Each inference costs compute — and money." },
  { term: "Hallucination", cat: "Data & AI", def: "When an AI states something false with confidence. Why human review (and RAG) matter for anything that counts." },
  { term: "Vector database", cat: "Data & AI", def: "A database that stores meaning as numbers, so an AI can find 'similar' things — the memory behind RAG and smart search." },
  { term: "Fine-tuning", cat: "Data & AI", def: "Further-training a general AI model on your own data so it specializes in your domain, format or style." },

  // Shipping & ops (more)
  { term: "Container", cat: "Shipping & ops", def: "A lightweight box that packages an app with everything it needs to run, so it behaves the same on any machine. Docker made them mainstream." },
  { term: "Serverless", cat: "Shipping & ops", def: "Running code without managing servers yourself — the cloud spins it up on demand and you pay only for what runs." },
  { term: "Monitoring", cat: "Shipping & ops", def: "Watching a live app's health — errors, speed, traffic — so problems are caught before users complain." },
  { term: "Scalability", cat: "Shipping & ops", def: "How well an app copes as usage grows from a hundred users to a million without falling over." },
];

/* Same slug used for term anchor ids and timeline chip links. */
const termSlug = (t) => "term-" + t.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");

/* A small map of the build process — which terms come into play, in order. */
const BUILD_STAGES = [
  { n: "01", name: "Design", blurb: "Decide what to build and how it looks and feels — before a line of code.", terms: ["UX", "UI", "Responsive design", "Accessibility (a11y)"] },
  { n: "02", name: "Set up", blurb: "Create the project, its home, and a way to track every change.", terms: ["Repository (repo)", "Git", "Framework", "Environment"] },
  { n: "03", name: "Build the frontend", blurb: "The part users actually see and tap, in the browser or app.", terms: ["Frontend", "Library", "SDK"] },
  { n: "04", name: "Build the backend", blurb: "The engine behind the screen — logic, data and the ways they talk.", terms: ["Backend", "Server", "Database", "API", "Endpoint", "CRUD"] },
  { n: "05", name: "Add intelligence", blurb: "Optional: weave in AI features, grounded in real data.", terms: ["LLM", "Prompt", "RAG", "Vector database"] },
  { n: "06", name: "Review & test", blurb: "Catch problems early, while they're cheap to fix.", terms: ["Pull request (PR)", "Bug", "Performance budget"] },
  { n: "07", name: "Ship it", blurb: "Make it live for real people — safely and repeatably.", terms: ["CI/CD", "Deployment", "Hosting", "Cloud"] },
  { n: "08", name: "Run & grow", blurb: "Keep it fast and healthy as more people show up.", terms: ["Cache", "Latency", "Monitoring", "Scalability"] },
];

/* CTA band on technologies.html — links to the dedicated, indexable page. */
function GlossarySection() {
  const peek = ["API", "CRUD", "Frontend", "Backend", "Cloud", "LLM"];
  return (
    <section className="section section--tight" data-screen-label="Plain-English glossary">
      <div className="container">
        <div className="glossary-cta">
          <div className="glossary-cta__text">
            <span className="eyebrow">Plain English</span>
            <h2 className="h2 section-head__title">Tech, without the jargon.</h2>
            <p className="lede">
              API, CRUD, frontend, backend — the words that get nodded at and never explained.
              We wrote a plain-English glossary so clients, students and the simply curious can
              follow any tech conversation. No gatekeeping; understanding is the whole point.
            </p>
            <div className="glossary-cta__actions">
              <a href="glossary.html" className="btn btn--primary">
                Open the glossary
                <span className="glossary-cta__count">{GLOSSARY_TERMS.length} terms</span>
              </a>
            </div>
          </div>
          <a className="glossary-cta__peek" href="glossary.html" aria-label="Open the glossary">
            {peek.map((term) => (
              <span key={term} className="glossary-chip">
                <span className="glossary-chip__term">{term}</span>
                <span className="glossary-chip__hint" aria-hidden="true">?</span>
              </span>
            ))}
            <span className="glossary-chip glossary-chip--more">+{GLOSSARY_TERMS.length - peek.length} more</span>
          </a>
        </div>
      </div>
    </section>
  );
}

/* Full, indexable glossary page — glossary.html */
function GlossaryPage() {
  const [query, setQuery] = React.useState("");

  React.useEffect(() => {
    document.title = "Tech glossary — plain-English terms — Innoveev";
    let m = document.head.querySelector('meta[name="description"]');
    if (!m) { m = document.createElement("meta"); m.setAttribute("name", "description"); document.head.appendChild(m); }
    m.setAttribute("content", "A plain-English glossary of technology terms — API, CRUD, frontend, backend, cloud, LLM and more — explained simply by Innoveev.");
  }, []);

  const q = query.trim().toLowerCase();
  const filtered = GLOSSARY_TERMS.filter(
    (t) => !q || t.term.toLowerCase().includes(q) || t.def.toLowerCase().includes(q)
  );
  const cats = [];
  filtered.forEach((t) => { if (!cats.includes(t.cat)) cats.push(t.cat); });

  return (
    <>
      <Nav />

      <header className="sub-hero">
        <div className="mesh" aria-hidden="true">
          <span className="mesh__blob mesh__blob--1"></span>
          <span className="mesh__blob mesh__blob--2"></span>
          <span className="mesh__blob mesh__blob--3"></span>
        </div>
        <div className="container">
          <div className="sub-hero__head">
            <span className="eyebrow">Plain English · Glossary</span>
            <h1 className="sub-hero__title">Tech, <em>explained simply.</em></h1>
            <p className="sub-hero__lede">
              {GLOSSARY_TERMS.length} terms that get nodded at and never explained — API, CRUD,
              frontend, backend, cloud, LLM and the rest. We wrote this so clients, students and
              the simply curious can follow any tech conversation. No gatekeeping.
            </p>
          </div>
        </div>
      </header>

      <section className="section section--tight" style={{ paddingTop: 0 }}>
        <div className="container">
          <div className="glossary-page__search">
            <svg width="18" height="18" viewBox="0 0 20 20" fill="none" aria-hidden="true">
              <circle cx="9" cy="9" r="6" stroke="currentColor" strokeWidth="1.6"/>
              <path d="m17 17-3.5-3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
            </svg>
            <input
              type="text"
              className="glossary-page__input"
              placeholder="Search terms — try “API” or “cloud”…"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              aria-label="Search glossary"
            />
            {query && (
              <button type="button" className="glossary-modal__clear" onClick={() => setQuery("")} aria-label="Clear search">
                <svg width="12" height="12" viewBox="0 0 14 14" fill="none"><path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
              </button>
            )}
          </div>

          {filtered.length === 0 ? (
            <div className="glossary-modal__empty">No term matches “{query}”. Ask us — we like the questions no one else answers.</div>
          ) : (
            cats.map((cat) => (
              <div key={cat} className="glossary-page__group">
                <h2 className="glossary-page__cat">{cat}</h2>
                <dl className="glossary-page__list">
                  {filtered.filter((t) => t.cat === cat).map((t) => (
                    <div key={t.term} className="glossary-page__item" id={termSlug(t.term)}>
                      <dt className="glossary-page__term">{t.term}</dt>
                      <dd className="glossary-page__def">{t.def}</dd>
                    </div>
                  ))}
                </dl>
              </div>
            ))
          )}
        </div>
      </section>

      <section className="section section--tight" data-screen-label="Build-process timeline">
        <div className="container">
          <div className="section-head">
            <div>
              <span className="eyebrow">The process</span>
              <h2 className="h2 section-head__title">When each piece shows up.</h2>
            </div>
            <p className="lede section-head__lede">
              A product gets built in roughly this order. Tap any term to jump to its plain-English definition.
            </p>
          </div>
          <ol className="gloss-timeline">
            {BUILD_STAGES.map((st) => (
              <li key={st.n} className="gloss-stage">
                <div className="gloss-stage__rail">
                  <span className="gloss-stage__num">{st.n}</span>
                  <span className="gloss-stage__line" aria-hidden="true"></span>
                </div>
                <div className="gloss-stage__body">
                  <h3 className="gloss-stage__name">{st.name}</h3>
                  <p className="gloss-stage__blurb">{st.blurb}</p>
                  <div className="gloss-stage__chips">
                    {st.terms.map((t) => (
                      <a key={t} href={"#" + termSlug(t)} className="gloss-stage__chip">{t}</a>
                    ))}
                  </div>
                </div>
              </li>
            ))}
          </ol>
        </div>
      </section>

      <section className="section section--tight">
        <div className="container">
          <div className="faq-closing">
            <h2 className="faq-closing__title">Still stuck on a <em>word?</em></h2>
            <p className="faq-closing__lede">
              We'd rather answer the question than have you nod along. Ask us anything — no such thing as a basic one.
            </p>
            <div className="faq-closing__ctas">
              <a href="contact.html" className="btn btn--primary">Ask us <Arrow /></a>
              <a href="technologies.html" className="btn btn--secondary">Explore our stack</a>
            </div>
          </div>
        </div>
      </section>

      <Footer />
      <TweaksUI />
      <StickyCTA />
      <CookieBanner />
      <CustomCursor enabled={window.useTweaksDefaults.cursor} />
      <BuildMode />
      <KeyboardEggs />
    </>
  );
}

window.GlossarySection = GlossarySection;
window.GlossaryPage = GlossaryPage;
