/* docs.jsx — two-step filter: 1/ account → 2/ doc type → list.
   No docs shown until an account is selected. Search and custom-doc CTA persist. */

const DOCS_DATA = {
  brokerage: {
    label: "Brokerage",
    statements: [
      { name: "April 2026", sub: "Account statement", meta: "PDF · 182 KB", recent: true },
      { name: "March 2026", sub: "Account statement", meta: "PDF · 176 KB" },
      { name: "February 2026", sub: "Account statement", meta: "PDF · 171 KB" },
      { name: "January 2026", sub: "Account statement", meta: "PDF · 168 KB" },
    ],
    tax: [
      { name: "1099-B", sub: "Proceeds from broker transactions", meta: "PDF · 240 KB", recent: true },
      { name: "Schedule D supplement", sub: "Capital gains detail", meta: "PDF · 118 KB" },
    ],
    agreements: [
      { name: "Account agreement", sub: "Brokerage terms", meta: "PDF" },
      { name: "Fee schedule", sub: "Wires, instant, expedited", meta: "PDF" },
      { name: "Privacy notice", sub: "How your data is handled", meta: "PDF" },
    ],
  },
  savings: {
    label: "Savings",
    statements: [
      { name: "April 2026", sub: "Account statement", meta: "PDF · 94 KB", recent: true },
      { name: "March 2026", sub: "Account statement", meta: "PDF · 91 KB" },
      { name: "February 2026", sub: "Account statement", meta: "PDF · 88 KB" },
    ],
    tax: [
      { name: "1099-INT", sub: "Interest income · Savings", meta: "PDF · 96 KB", recent: true },
    ],
    agreements: [
      { name: "Account agreement", sub: "Deposit & savings terms", meta: "PDF" },
      { name: "E-sign consent", sub: "Electronic delivery", meta: "PDF" },
    ],
  },
  roth: {
    label: "Roth IRA",
    statements: [
      { name: "April 2026", sub: "Account statement", meta: "PDF · 138 KB", recent: true },
      { name: "March 2026", sub: "Account statement", meta: "PDF · 134 KB" },
    ],
    tax: [
      { name: "Form 5498", sub: "IRA contribution information", meta: "PDF · 82 KB", recent: true },
    ],
    agreements: [
      { name: "IRA agreement", sub: "Roth IRA plan document", meta: "PDF" },
      { name: "Fee schedule", sub: "IRA maintenance fees", meta: "PDF" },
    ],
  },
  crypto: {
    label: "Crypto",
    statements: [
      { name: "April 2026", sub: "Account statement", meta: "PDF · 108 KB", recent: true },
      { name: "March 2026", sub: "Account statement", meta: "PDF · 103 KB" },
    ],
    tax: [
      { name: "1099-DA", sub: "Digital asset proceeds", meta: "PDF · 118 KB", recent: true },
      { name: "Crypto gain / loss", sub: "Cost-basis summary", meta: "CSV · 64 KB" },
    ],
    agreements: [
      { name: "Crypto account agreement", sub: "Digital asset terms", meta: "PDF" },
      { name: "Risk disclosure", sub: "Digital asset risks", meta: "PDF" },
    ],
  },
};

const ACCOUNT_KEYS = Object.keys(DOCS_DATA);

const DOC_TYPES = [
  { id: "statements", label: "Statements" },
  { id: "tax",        label: "Tax" },
  { id: "agreements", label: "Agreements" },
];

const DocumentsHub = ({ onClose, nav, flash, initialAcct }) => {
  const [query, setQuery]       = useState("");
  const [acct, setAcct]         = useState(initialAcct || null);   // brokerage | savings | roth | crypto
  const [docType, setDocType]   = useState(null);   // statements | tax | agreements | null = all

  const q = query.trim().toLowerCase();

  /* derive visible docs from selections + search */
  const visibleDocs = (() => {
    if (!acct && !q) return [];

    let pool = [];

    const collectFrom = (key) => {
      const bucket = DOCS_DATA[key];
      const types = docType ? [docType] : DOC_TYPES.map(t => t.id);
      types.forEach(t => {
        (bucket[t] || []).forEach(d => pool.push({ ...d, _type: t, _acct: key }));
      });
    };

    if (acct) {
      collectFrom(acct);
    } else if (q) {
      ACCOUNT_KEYS.forEach(collectFrom);
    }

    if (q) {
      pool = pool.filter(d => (d.name + " " + d.sub).toLowerCase().includes(q));
    }
    return pool;
  })();

  const build = () => {
    onClose();
    nav.ask(
      "Build me a custom report.",
      "Happy to. Tell me what and over what period — realized gains, interest earned, a cashflow summary, a full transaction export, all of it — and I'll generate a clean PDF you can download or send straight to your accountant. Want it for this year, or a specific range?"
    );
  };

  const get = (d) => flash(`Downloading ${d.name}…`);

  const pillBase = {
    flex: "none", padding: "7px 13px", borderRadius: 999, whiteSpace: "nowrap",
    fontFamily: "var(--f-display)", fontSize: 12.5, fontWeight: 600,
    border: "none", cursor: "pointer",
    background: "color-mix(in srgb, var(--ink) 8%, var(--bg-2))", color: "var(--ink-2)",
    transition: "background 140ms ease, color 140ms ease",
  };
  const pillActive = {
    background: "var(--ink)", color: "var(--bg)",
  };

  const showList = acct && !q;
  const showSearchResults = q && visibleDocs.length > 0;
  const showEmpty = (acct || q) && visibleDocs.length === 0;

  return (
    <div className="push-enter" style={{ position: "absolute", inset: 0, zIndex: 320, background: "var(--bg)", display: "flex", flexDirection: "column" }} data-screen-label="Documents">
      {window.StatusBar && <window.StatusBar />}
      <NavBar title="Documents"
        right={<button className="press" onClick={onClose} style={{ background: "none", border: "none", color: "var(--ink-3)", display: "flex" }}><Icon name="close" size={20} /></button>} />

      <div className="scroll" style={{ padding: "10px 0 32px" }}>

        {/* build-with-Yoshi CTA */}
        <div style={{ padding: "0 18px" }}>
          <button className="press" onClick={build} style={{
            width: "100%", textAlign: "left", display: "flex", alignItems: "center", gap: 13, padding: "14px 15px",
            background: "color-mix(in srgb, var(--accent) 12%, var(--bg-card))", border: "1px solid var(--accent)", borderRadius: 12, cursor: "pointer",
          }}>
            <span style={{ width: 38, height: 38, flex: "none", borderRadius: 999, background: "var(--accent)", display: "grid", placeItems: "center" }}>
              <Icon name="doc" size={18} color="var(--accent-ink)" />
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: "var(--f-display)", fontSize: 14.5, fontWeight: 600, letterSpacing: "-0.01em" }}>Build a custom doc or report</div>
              <div style={{ fontFamily: "var(--f-display)", fontSize: 11.5, color: "var(--ink-2)", marginTop: 2, lineHeight: 1.4 }}>Realized gains, cashflow, a transaction export. Yoshi will tell you when it's ready.</div>
            </div>
            <Icon name="back" size={16} color="var(--accent)" style={{ transform: "scaleX(-1)" }} />
          </button>
        </div>

        {/* step 1: account dropdown */}
        {!q && (
          <div style={{ marginTop: 16, padding: "0 18px" }}>
            <div style={{ marginBottom: 8 }}><Eyebrow>Account</Eyebrow></div>
            <div style={{ position: "relative" }}>
              <select
                value={acct || ""}
                onChange={e => { setAcct(e.target.value || null); setDocType(null); }}
                style={{
                  width: "100%", appearance: "none", WebkitAppearance: "none",
                  background: "var(--bg-2)", border: "1px solid var(--rule-2)", borderRadius: 10,
                  padding: "10px 36px 10px 13px", fontFamily: "var(--f-display)", fontSize: 14,
                  fontWeight: 500, color: acct ? "var(--ink)" : "var(--ink-3)", outline: "none", cursor: "pointer",
                }}>
                <option value="">Select an account…</option>
                {ACCOUNT_KEYS.map(key => (
                  <option key={key} value={key}>{DOCS_DATA[key].label}</option>
                ))}
              </select>
              <span style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", pointerEvents: "none", color: "var(--ink-3)" }}>
                <Icon name="back" size={14} style={{ transform: "rotate(90deg)" }} />
              </span>
            </div>
          </div>
        )}

        {/* step 2: doc type pills — only after account selected */}
        {acct && !q && (
          <div style={{ marginTop: 14 }}>
            <div style={{ padding: "0 18px 8px" }}><Eyebrow>Type</Eyebrow></div>
            <div className="hcar" style={{ display: "flex", gap: 7, overflowX: "auto", padding: "2px 18px 4px" }}>
              {DOC_TYPES.map(t => {
                const active = docType === t.id;
                return (
                  <button key={t.id} className="press"
                    onClick={() => setDocType(active ? null : t.id)}
                    style={{ ...pillBase, ...(active ? pillActive : {}) }}>
                    {t.label}
                  </button>
                );
              })}
            </div>
          </div>
        )}

        {/* search — only after account selected, below type pills */}
        {acct && (
          <div style={{ padding: "13px 18px 0" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "10px 13px", background: "var(--bg-2)", border: "1px solid var(--rule-2)", borderRadius: 10 }}>
              <Icon name="search" size={16} color="var(--ink-3)" stroke={1.5} />
              <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search documents"
                style={{ flex: 1, border: "none", background: "transparent", outline: "none", color: "var(--ink)", fontFamily: "var(--f-display)", fontSize: 14 }} />
              {query && <button className="press" onClick={() => setQuery("")} style={{ background: "none", border: "none", display: "flex", color: "var(--ink-3)", padding: 0 }}><Icon name="close" size={15} /></button>}
            </div>
          </div>
        )}

        {/* empty prompt — no account selected yet */}
        {!acct && !q && (
          <div style={{ padding: "36px 18px", textAlign: "center" }}>
            <div style={{ fontFamily: "var(--f-display)", fontSize: 13, color: "var(--ink-3)", lineHeight: 1.6 }}>Select an account to view your documents.</div>
          </div>
        )}

        {/* no results */}
        {showEmpty && (
          <div style={{ padding: "30px 18px", textAlign: "center", fontFamily: "var(--f-display)", fontSize: 13, color: "var(--ink-3)" }}>
            {q ? `No documents match "${query}".` : "No documents for this selection."}
          </div>
        )}

        {/* doc list */}
        {(showList || showSearchResults) && visibleDocs.length > 0 && (
          <div style={{ marginTop: 18, borderTop: "1px solid var(--rule)" }}>
            {visibleDocs.map((d, i) => (
              <button key={d.name + i} className="press" onClick={() => get(d)}
                style={{ width: "100%", display: "grid", gridTemplateColumns: "34px 1fr auto", gap: 12, alignItems: "center", padding: "11px 18px", background: "none", border: "none", borderBottom: "1px solid var(--rule)", textAlign: "left", cursor: "pointer" }}>
                <span style={{ width: 34, height: 34, display: "grid", placeItems: "center" }}>
                  <Icon name="doc" size={18} stroke={1.5} color="var(--ink-2)" />
                </span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                    <span style={{ fontFamily: "var(--f-display)", fontSize: 13.5, fontWeight: 500 }}>{d.name}</span>

                  </div>
                  <div style={{ fontFamily: "var(--f-display)", fontSize: 11, color: "var(--ink-3)", marginTop: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.sub}</div>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <span style={{ fontFamily: "var(--f-mono)", fontSize: 10, color: "var(--ink-3)", whiteSpace: "nowrap" }}>{d.meta}</span>
                  <Icon name="download" size={17} color="var(--ink-3)" />
                </div>
              </button>
            ))}
          </div>
        )}

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

window.DocumentsHub = DocumentsHub;
