/* Screens: Landing, Category select, Product select + tray — Spec Compare */

/* ---------- Landing ---------- */
function LandingScreen({ recents, onStart, onOpenRecent }) {
  const db = window.SPECDB;
  return (
    <div className="screen landing" data-screen-label="Landing">
      <div className="landing-hero">
        <div className="landing-kicker">
          <span className="kicker-dot"></span> Sales Engineering Tool
        </div>
        <h1 className="landing-title">Compare scan engines across<br />every vendor, instantly.</h1>
        <p className="landing-sub">
          Side-by-side specs for {db.products.length} engines from {Object.keys(db.brands).length} vendors — built for live customer calls.
        </p>
        <button className="btn btn-primary btn-lg" onClick={onStart}>
          Start a comparison <Icons.arrowR size={17} />
        </button>
      </div>

      <div className="landing-lower">
        <div className="landing-recents">
          <div className="landing-sectiontitle"><Icons.clock size={14} /> Recent comparisons</div>
          {recents.length === 0 ?
          <div className="recent-empty">Your recent comparisons will appear here.</div> :

          <div className="recent-list">
              {recents.map((r, i) => {
              const prods = r.ids.map((id) => db.find(id)).filter(Boolean);
              if (prods.length < 2) return null;
              return (
                <button key={i} className="recent-item" onClick={() => onOpenRecent(r.ids)}>
                    <span className="recent-chips">
                      {prods.map((p) =>
                    <span key={p.id} className="recent-mark" style={{ background: db.brands[p.brand].color, color: db.brands[p.brand].text }}>
                          {db.brands[p.brand].name[0]}
                        </span>
                    )}
                    </span>
                    <span className="recent-names">{prods.map((p) => p.model).join("  ·  ")}</span>
                    <span className="recent-cat">{prods[0].specs.categoryName}</span>
                    <Icons.chevR size={15} style={{ opacity: 0.45 }} />
                  </button>);

            })}
            </div>
          }
        </div>
        <div className="landing-brands">
          <div className="landing-sectiontitle">In the database</div>
          <div className="landing-brandgrid">
            {Object.values(db.brands).map((b) =>
            <span key={b.id} className="brandchip brandchip-md">
                <span className="brandchip-mark" style={{ background: b.color, color: b.text }}>{b.name[0]}</span>
                <span className="brandchip-name">{b.name}</span>
                <span className="brandcount">{db.products.filter((p) => p.brand === b.id).length}</span>
              </span>
            )}
          </div>
        </div>
      </div>
    </div>);

}

/* Committed category cover images — these override the product-derived photo
   so every salesperson sees the same image (the in-app drop is dev-only and
   not shared). Drop the files in /images with these exact names. */
const CATEGORY_IMAGES = {
  "decoded-scan-engine":     "images/cat-decoded.png",
  "undecoded-scan-engine":   "images/cat-undecoded.png",
  "fixed-mount-module":      "images/cat-fixed-mount.png",
  "customer-facing-modules": "images/cat-customer-facing.png",
};

/* Per-category accent + tag for the animated feature card. Falls back to a
   cycling color and the category name if a new category id appears. */
const CATEGORY_CARD = {
  "decoded-scan-engine":     { color: "blue",   tag: "Decoded" },
  "undecoded-scan-engine":   { color: "purple", tag: "Undecoded" },
  "fixed-mount-module":      { color: "orange", tag: "Fixed Mount" },
  "customer-facing-modules": { color: "green",  tag: "Customer Facing" },
};
/* HSL triples → --feat (accent), --feat-light (glow), --feat-dark (tag bg) */
const FEAT_COLORS = {
  orange: { c: "hsl(35,91%,52%)",  l: "hsl(41,100%,85%)",  d: "hsl(41,100%,95%)" },
  purple: { c: "hsl(262,80%,58%)", l: "hsl(261,100%,88%)", d: "hsl(264,100%,97%)" },
  blue:   { c: "hsl(211,95%,55%)", l: "hsl(210,100%,85%)", d: "hsl(214,100%,96%)" },
  green:  { c: "hsl(155,60%,38%)", l: "hsl(155,55%,84%)",  d: "hsl(155,55%,95%)" },
};
const COLOR_ORDER = ["blue", "purple", "orange", "green"];

/* ---------- Step 1: category ---------- */
function CategoryScreen({ onPick }) {
  const db = window.SPECDB;
  return (
    <div className="screen" data-screen-label="Step 1 — Category">
      <div className="stephead">
        <h2 className="steptitle">Select a product category</h2>
        <p className="stepsub">Pick the family in which you want to compare the products</p>
      </div>
      <div className="catgrid">
        {db.categories.map((c, i) => {
          const cover    = db.inCategory(c.id).find((p) => p.image);
          const coverSrc = CATEGORY_IMAGES[c.id] || (cover ? cover.image : undefined);
          const meta     = CATEGORY_CARD[c.id] || {};
          const cv       = FEAT_COLORS[meta.color || COLOR_ORDER[i % COLOR_ORDER.length]];
          const tag      = meta.tag || c.name;
          const count    = db.inCategory(c.id).length;
          return (
            <div
              key={c.id}
              className="catcard"
              role="button"
              tabIndex={0}
              style={{ "--feat": cv.c, "--feat-light": cv.l, "--feat-dark": cv.d }}
              onClick={() => onPick(c.id)}
              onKeyDown={(e) => {if (e.key === "Enter" || e.key === " ") {e.preventDefault();onPick(c.id);}}}>
              <span className="catcard-glow" aria-hidden="true"></span>
              <span className="catcard-index">{String(i + 1).padStart(3, "0")}</span>
              <div className="catcard-imgwrap">
                {coverSrc ? <img className="catcard-img" src={coverSrc} alt={c.name} /> : null}
              </div>
              <div className="catcard-panel">
                <span className="catcard-tag">{tag}</span>
                <div className="catcard-name">{c.name}</div>
                <div className="catcard-desc">{c.desc}</div>
                <span className="catcard-count">{count} products <Icons.chevR size={13} /></span>
              </div>
            </div>);

        })}
      </div>
    </div>);

}

/* ---------- Step 2: product select ---------- */
function SelectScreen({ category, selection, onToggle, onCompare, onBack, onClear }) {
  const db = window.SPECDB;
  const cat = db.categories.find((c) => c.id === category);
  const [query, setQuery] = React.useState("");
  const [brandFilter, setBrandFilter] = React.useState(null); /* single-select: brand id or null = all */
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    setLoading(true);
    const t = setTimeout(() => setLoading(false), 520);
    return () => clearTimeout(t);
  }, [category]);

  const all = db.inCategory(category);
  const brandsInCat = Object.values(db.brands).filter((b) => all.some((p) => p.brand === b.id));
  const q = query.trim().toLowerCase();
  const visible = all.filter((p) =>
  (!brandFilter || p.brand === brandFilter) && (
  !q || (p.model + " " + db.brands[p.brand].name + " " + p.preview.join(" ")).toLowerCase().includes(q))
  );

  /* Single-select: clicking the active chip clears it */
  const toggleBrand = (id) =>
  setBrandFilter((f) => f === id ? null : id);

  const selectedProducts = selection.map((id) => db.find(id)).filter(Boolean);
  const full = selection.length >= 4;

  return (
    <div className="screen" data-screen-label="Step 2 — Select products">
      <div className="stephead stephead-row">
        <div>
          <button className="backlink" onClick={onBack}><Icons.arrowL size={14} /> Categories</button>
          <h2 className="steptitle">{cat.name}</h2>
          <p className="stepsub">Pick 2–4 products to compare — mix brands freely.</p>
        </div>
        <div className="selecttools">
          <div className="searchbox">
            <Icons.search size={15} />
            <input
              type="text" placeholder={"Search " + all.length + " products…"}
              value={query} onChange={(e) => setQuery(e.target.value)} aria-label="Search products" />
            
            {query ? <button className="searchclear" onClick={() => setQuery("")}><Icons.x size={13} /></button> : null}
          </div>
          <div className="brandfilters">
            {brandsInCat.map((b) =>
            <button
              key={b.id}
              className={"filterchip" + (brandFilter === b.id ? " filterchip-on" : "")}
              onClick={() => toggleBrand(b.id)}>
              
                <span className="filterchip-dot" style={{ background: b.color }}></span>{b.name}
              </button>
            )}
          </div>
        </div>
      </div>

      {loading ?
      <div className="prodgrid">{all.map((_, i) => <SkeletonCard key={i} />)}</div> :
      visible.length === 0 ?
      <div className="emptystate">
          No products match {query ? <>“{query}”</> : "those filters"}.
          <button className="btn btn-ghost" onClick={() => {setQuery("");setBrandFilter(null);}}>Clear filters</button>
        </div> :

      <div className="prodgrid">
          {visible.map((p) =>
        <ProductCard
          key={p.id} product={p}
          selected={selection.includes(p.id)}
          disabled={full}
          onToggle={onToggle} />

        )}
        </div>
      }

      {/* Sticky selection tray */}
      <div className={"tray" + (selection.length > 0 ? " tray-visible" : "")} role="region" aria-label="Selected products">
        <div className="tray-slots">
          {selectedProducts.map((p) =>
          <span key={p.id} className="tray-chip">
              <span className="recent-mark" style={{ background: db.brands[p.brand].color, color: db.brands[p.brand].text }}>
                {db.brands[p.brand].name[0]}
              </span>
              {p.model}
              <button className="tray-x" onClick={() => onToggle(p.id)} aria-label={"Remove " + p.model}><Icons.x size={12} /></button>
            </span>
          )}
          {Array.from({ length: Math.max(0, 2 - selection.length) }).map((_, i) =>
          <span key={"empty" + i} className="tray-chip tray-chip-empty">{selection.length + i === 0 ? "Pick a product" : "Pick one more"}</span>
          )}
        </div>
        <div className="tray-actions">
          <span className="tray-count">{selection.length} of 4</span>
          {selection.length > 0 ? <button className="btn btn-ghost" onClick={onClear}>Clear</button> : null}
          <button className="btn btn-primary" disabled={selection.length < 2} onClick={onCompare}>
            Compare now <Icons.arrowR size={15} />
          </button>
        </div>
      </div>
    </div>);

}

/* ---------- Data admin: Excel upload ---------- */
function DataScreen({ onApplied, onBack, onExitAdmin }) {
  const db = window.SPECDB;
  const meta = db.meta;
  const [busy, setBusy] = React.useState(false);
  const [drag, setDrag] = React.useState(false);
  const fileRef = React.useRef(null);

  const apply = async (file) => {
    if (!file || busy) return;
    if (!/\.(xlsx|xlsm)$/i.test(file.name)) {
      window.toast("Please upload an Excel file (.xlsx)", "x");
      return;
    }
    setBusy(true);
    try {
      const raw = await window.ScanIQImport.parseXlsx(await file.arrayBuffer(), file.name);
      /* Apply locally first (assemble + cache + refresh UI) so the upload feels instant */
      window.ScanIQDB.applyCatalog(raw);
      /* Then persist to the shared store so the whole team sees it and it survives deploys */
      try {
        await window.ScanIQDB.saveRemote(raw);
        window.toast(`Database updated — ${raw.products.length} products, saved for the whole team`, "check");
      } catch (err) {
        console.error(err);
        window.toast("Updated on this device, but the team-wide save failed: " + err.message, "x");
      }
      onApplied();
    } catch (err) {
      console.error(err);
      window.toast("Import failed: " + err.message, "x");
    }
    setBusy(false);
  };

  const revert = async () => {
    localStorage.removeItem("scaniq-imported-db-v1");
    window.SPECDB = window.__DEFAULT_SPECDB;
    window.dispatchEvent(new Event("scaniq-db-updated"));
    try {
      await window.ScanIQDB.clearRemote();
      window.toast("Reverted to built-in sample data for everyone", "check");
    } catch (err) {
      console.error(err);
      window.toast("Reverted on this device, but the team-wide revert failed: " + err.message, "x");
    }
    onApplied();
  };

  return (
    <div className="screen screen-data" data-screen-label="Data — update database">
      <div className="stephead">
        <button className="backlink" onClick={onBack}><Icons.arrowL size={14} /> Back</button>
        <h2 className="steptitle">Product database</h2>
        <p className="stepsub">Owner-only tools — upload the spec workbook to update every screen: products, images, aimer views and spec tables.</p>
      </div>

      <div
        className={"dropzone" + (drag ? " dropzone-drag" : "") + (busy ? " dropzone-busy" : "")}
        onDragOver={(e) => {e.preventDefault();setDrag(true);}}
        onDragLeave={() => setDrag(false)}
        onDrop={(e) => {e.preventDefault();setDrag(false);apply(e.dataTransfer.files && e.dataTransfer.files[0]);}}
        onClick={() => fileRef.current && fileRef.current.click()}
        role="button" tabIndex={0}
        onKeyDown={(e) => {if (e.key === "Enter" || e.key === " ") {e.preventDefault();fileRef.current && fileRef.current.click();}}}>
        
        <span className="dropzone-icon"><Icons.doc size={26} /></span>
        <span className="dropzone-title">{busy ? "Importing…" : "Drop your Excel file here"}</span>
        <span className="dropzone-sub">{busy ? "Parsing workbook" : "or click to browse — .xlsx, one column per product"}</span>
        <input ref={fileRef} type="file" accept=".xlsx,.xlsm" hidden
        onChange={(e) => {apply(e.target.files && e.target.files[0]);e.target.value = "";}} />
      </div>

      <div className="datasource">
        <div className="datasource-row">
          <span className="datasource-label">Current source</span>
          <span className="datasource-value">{meta ? meta.sourceName : "Built-in sample data"}</span>
        </div>
        {meta ?
        <div className="datasource-row">
            <span className="datasource-label">Imported</span>
            <span className="datasource-value">{new Date(meta.importedAt).toLocaleString()}</span>
          </div> :
        null}
        <div className="datasource-row">
          <span className="datasource-label">Products</span>
          <span className="datasource-value">{db.products.length} across {db.categories.map((c) => `${db.inCategory(c.id).length} ${c.name}`).join(" · ")}</span>
        </div>
        {meta ?
        <div className="datasource-row">
            <span className="datasource-label"></span>
            <button className="btn btn-outline btn-sm" onClick={revert}>Revert to sample data</button>
          </div> :
        null}
      </div>

      <div className="adminnote">
        <span>These tools are only visible in owner mode on this device.</span>
        <button className="btn btn-ghost btn-sm" onClick={onExitAdmin}>Hide admin tools</button>
      </div>
    </div>);

}

Object.assign(window, { LandingScreen, CategoryScreen, SelectScreen, DataScreen });