/* 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 NON_ACCOUNT_DOCS = [
  { name: "E-sign consent", sub: "Electronic delivery and signature consent", meta: "Link", href: "https://yoshi.ai/esign-consent/" },
  { name: "Cash account disclosures", sub: "Column N.A. banking terms and authorizations", meta: "Link", href: "https://yoshi.ai/cash-account-disclosures" },
  { name: "Column N.A. legal terms", sub: "Banking services · Member FDIC", meta: "Link", href: "https://column.com/legal" },
  { name: "Customer Account Agreement", sub: "Apex Clearing Corporation", meta: "PDF link", href: "https://storage.googleapis.com/apexclearing-account-agreements-prd-00/SCAA-OBD-20260318-EN.pdf" },
  { name: "Customer Information Brochure", sub: "Apex Clearing Corporation", meta: "PDF link", href: "https://library.apexfintechsolutions.com/wp-content/uploads/2024/12/Apex-Direct-Customer-Infromation-Brochure.pdf" },
  { name: "Apex Privacy Policy", sub: "Apex Clearing Corporation", meta: "PDF link", href: "https://library.apexfintechsolutions.com/wp-content/uploads/2025/04/AFBS-Privacy-Policy.pdf" },
  { name: "Apex Terms of Service", sub: "Apex Clearing Corporation", meta: "PDF link", href: "https://library.apexfintechsolutions.com/wp-content/uploads/2025/04/AFBS-Terms-of-Service-Template.pdf" },
  { name: "CIP Notice", sub: "Customer identification program", meta: "PDF link", href: "https://library.apexfintechsolutions.com/wp-content/uploads/2025/04/FINRA-CIP-Notice.pdf" },
  { name: "Business Continuity Plan", sub: "Apex Clearing Corporation", meta: "PDF link", href: "https://library.apexfintechsolutions.com/wp-content/uploads/2024/12/Business-Continuity-Plan-Policy-11-08-2024.pdf" },
  { name: "Apex Fee Sheet", sub: "Brokerage fees and services", meta: "PDF link", href: "https://library.apexfintechsolutions.com/wp-content/uploads/2024/12/Apex-Direct-Misc-Services-Fee-Sheet-11.2024.pdf" },
];

const ACCOUNT_KEYS = Object.keys(DOCS_DATA);
const ACCOUNT_FILTERS = [{ id: "all", label: "All accounts" }, ...ACCOUNT_KEYS.map((key) => ({ id: key, label: DOCS_DATA[key].label })), { id: "non-account", label: "Non-account related documents" }];

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 || "all");   // all | brokerage | savings | roth | crypto | non-account
  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 }));
      });
    };

    const collectNonAccount = () => {
      NON_ACCOUNT_DOCS.forEach(d => pool.push({ ...d, _type: "onboarding", _acct: "non-account" }));
    };

    if (acct === "all") {
      ACCOUNT_KEYS.forEach(collectFrom);
    } else if (acct === "non-account") {
      collectNonAccount();
    } else if (acct) {
      collectFrom(acct);
    } else if (q) {
      ACCOUNT_KEYS.forEach(collectFrom);
      collectNonAccount();
    }

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

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

  const pillBase = {
    flex: "none", padding: "7px 13px", borderRadius: 999, whiteSpace: "nowrap",
    fontFamily: "var(--f-display)", fontSize: typeSize(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 = !q && visibleDocs.length > 0;
  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" }}>

        {/* step 1: account dropdown */}
        {!q && (
          <div style={{ marginTop: 0, 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: typeSize(14),
                  fontWeight: 500, color: "var(--ink)", outline: "none", cursor: "pointer",
                }}>
                {ACCOUNT_FILTERS.map(filter => (
                  <option key={filter.id} value={filter.id}>{filter.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 !== "non-account" && !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: typeSize(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: typeSize(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: typeSize(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) => {
              const rowStyle = { 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", color: "inherit", textDecoration: "none" };
              const rowContent = (
                <>
                <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: typeSize(13.5), fontWeight: 500 }}>{d.name}</span>

                  </div>
                  <div style={{ fontFamily: "var(--f-display)", fontSize: typeSize(11), color: "var(--ink-3)", marginTop: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{acct === "all" ? `${DOCS_DATA[d._acct]?.label || "Onboarding"} · ${d.sub}` : d.sub}</div>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <span style={{ fontFamily: "var(--f-mono)", fontSize: typeSize(10), color: "var(--ink-3)", whiteSpace: "nowrap" }}>{d.meta}</span>
                  <Icon name={d.href ? "external" : "download"} size={17} color="var(--ink-3)" />
                </div>
                </>
              );
              return d.href ? (
                <a key={d.name + i} className="press" href={d.href} target="_blank" rel="noopener noreferrer" onClick={() => get(d)} style={rowStyle}>
                  {rowContent}
                </a>
              ) : (
                <button key={d.name + i} className="press" onClick={() => get(d)} style={rowStyle}>
                  {rowContent}
                </button>
              );
            })}
          </div>
        )}

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

window.DocumentsHub = DocumentsHub;
