// AccountsScreen — connected data sources + chart of accounts

(function () {
  const fmt = (n, ccy) => {
    if (n == null || isNaN(n)) return "—";
    const abs = Math.abs(n);
    const isInt = ccy === "KRW" || ccy === "JPY" || Math.abs(abs - Math.round(abs)) < 0.005;
    return (n < 0 ? "− " : "") + abs.toLocaleString(undefined, {
      minimumFractionDigits: isInt ? 0 : 2,
      maximumFractionDigits: isInt ? 0 : 2,
    });
  };

  const entityShort = { personal: "P/", tfox: "9T/", finacode: "FC/" };
  const entityClass = { personal: "personal", tfox: "tfox", finacode: "finacode" };

  // ----- Status pill --------------------------------------------------
  function StatusPill({ status }) {
    const map = {
      ok:   { lbl: "OK",      cls: "ok" },
      warn: { lbl: "WARN",    cls: "warn" },
      fail: { lbl: "FAILED",  cls: "fail" },
      idle: { lbl: "IDLE",    cls: "idle" },
    };
    const m = map[status] || map.idle;
    return <span className={`acct-pill acct-pill-${m.cls}`}><span className="acct-pill-dot"></span>{m.lbl}</span>;
  }

  function MethodTag({ method }) {
    const map = {
      "api":       "API",
      "csv-poll":  "CSV · POLL",
      "csv-drop":  "CSV · DROP",
      "manual":    "MANUAL",
    };
    return <span className="acct-method">{map[method] || method.toUpperCase()}</span>;
  }

  // ----- Connected source card ---------------------------------------
  function SourceCard({ src, selected, onClick }) {
    return (
      <button className={`acct-src-card ${selected ? "selected" : ""}`} onClick={onClick}>
        <div className="acct-src-head">
          <span className={`entity-badge ${entityClass[src.entity]}`}>{entityShort[src.entity]}</span>
          <StatusPill status={src.status} />
        </div>
        <div className="acct-src-name">{src.name}</div>
        <div className="acct-src-meta">
          <span className="acct-src-no">{src.maskedNo}</span>
          <span className="acct-src-country">· {src.country}</span>
        </div>
        <div className="acct-src-balance">
          <span className="acct-src-balance-val">{fmt(src.balance, src.ccy)}</span>
          <span className="ccy"> {src.ccy}</span>
        </div>
        <div className="acct-src-foot">
          <MethodTag method={src.method} />
          <span className="acct-src-sync">SYNC&nbsp;{src.lastSync.split(" ")[1]}</span>
        </div>
      </button>
    );
  }

  // ----- Chart of accounts tree --------------------------------------
  // accountsByEntity rows have full path; we render them grouped per entity, indented by depth.
  function ChartOfAccounts({ entity }) {
    const data = window.AKEFIN_DATA.accountsByEntity;
    const sets = entity === "all"
      ? [["Personal", data.personal, "personal"], ["9TFox", data.tfox, "tfox"], ["Finacode", data.finacode, "finacode"]]
      : [[entity === "tfox" ? "9TFox" : entity[0].toUpperCase() + entity.slice(1), data[entity], entity]];

    return (
      <div className="acct-coa">
        {sets.map(([title, rows, cls]) => (
          <div key={title} className="acct-coa-group">
            <div className="acct-coa-head">
              <span className={`entity-badge ${entityClass[cls]}`}>{entityShort[cls]}</span>
              <span className="acct-coa-title">{title}</span>
              <span className="acct-coa-count">{rows.length} accounts</span>
            </div>
            <div className="acct-coa-rows">
              {rows.map((r) => {
                const depth = (r.path.match(/:/g) || []).length;
                const leaf = r.path.split(":").pop();
                return (
                  <div key={r.path} className={`acct-coa-row ${r.kind}`}>
                    <span className="acct-coa-tree" style={{ paddingLeft: depth * 18 }}>
                      <span className="acct-coa-glyph">{r.kind === "branch" ? "▸" : "·"}</span>
                      <span className="acct-coa-leaf">{leaf}</span>
                    </span>
                    <span className="acct-coa-path mono">{r.path}</span>
                    <span className={`acct-coa-amt mono ${r.balance < 0 ? "neg" : "pos"}`}>
                      {r.balance >= 0 ? "+ " : "− "}{fmt(Math.abs(r.balance), r.ccy)}
                      <span className="ccy"> {r.ccy}</span>
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    );
  }

  // ----- Detail panel for a selected source --------------------------
  function SourceDetail({ src }) {
    if (!src) {
      return (
        <div className="acct-detail acct-detail-empty">
          <div className="acct-detail-empty-lbl">SELECT A SOURCE</div>
          <div className="acct-detail-empty-sub">Click a connected account to inspect sync settings, recent imports, and rotation.</div>
        </div>
      );
    }
    return (
      <div className="acct-detail">
        <div className="acct-detail-head">
          <div>
            <div className="acct-detail-eyebrow">{src.kind.toUpperCase()} · {src.country}</div>
            <h2 className="acct-detail-title">{src.name}</h2>
            <div className="acct-detail-sub mono">{src.maskedNo}</div>
          </div>
          <StatusPill status={src.status} />
        </div>

        <div className="acct-detail-stat-grid">
          <div className="acct-detail-stat">
            <div className="lbl">BALANCE</div>
            <div className="val">{fmt(src.balance, src.ccy)}<span className="ccy"> {src.ccy}</span></div>
          </div>
          <div className="acct-detail-stat">
            <div className="lbl">TX · 30D</div>
            <div className="val">{src.txCount30d}</div>
          </div>
          <div className="acct-detail-stat">
            <div className="lbl">LAST SYNC</div>
            <div className="val">{src.lastSync.split(" ")[1]}</div>
            <div className="sub">{src.lastSync.split(" ")[0]}</div>
          </div>
          <div className="acct-detail-stat">
            <div className="lbl">NEXT</div>
            <div className="val">{src.nextRun}</div>
          </div>
        </div>

        <div className="acct-detail-section">
          <div className="acct-detail-section-head">SYNC</div>
          <div className="acct-kv-row"><span className="k">METHOD</span><span className="v"><MethodTag method={src.method} /></span></div>
          <div className="acct-kv-row"><span className="k">ENTITY</span><span className="v"><span className={`entity-badge ${entityClass[src.entity]}`}>{entityShort[src.entity]}</span>&nbsp;{src.entity === "tfox" ? "9TFox" : src.entity[0].toUpperCase() + src.entity.slice(1)}</span></div>
          <div className="acct-kv-row"><span className="k">SCHEDULE</span><span className="v mono">{src.method === "api" ? "every 4 hours" : src.method === "csv-poll" ? "every 12 hours" : "on demand"}</span></div>
          <div className="acct-kv-row"><span className="k">CCY</span><span className="v mono">{src.ccy}</span></div>
        </div>

        <div className="acct-detail-section">
          <div className="acct-detail-section-head">RECENT IMPORTS</div>
          <div className="acct-mini-log">
            <div className="acct-mini-row">
              <span className="t">{src.lastSync.split(" ")[1]}</span>
              <span className="msg">Last successful sync · {src.txCount30d} rows in 30d</span>
            </div>
            {src.status === "fail" && (
              <div className="acct-mini-row fail">
                <span className="t">{src.lastSync.split(" ")[1]}</span>
                <span className="msg">CSV parse failed · encoding mismatch</span>
              </div>
            )}
            {src.status === "warn" && (
              <div className="acct-mini-row warn">
                <span className="t">{src.lastSync.split(" ")[1]}</span>
                <span className="msg">11 rows queued for review · 3 failed</span>
              </div>
            )}
          </div>
        </div>

        <div className="acct-detail-actions">
          <button className="btn"><Icon name="refresh" size={13} /> Sync now</button>
          <button className="btn">Rotate credentials</button>
          <button className="btn ghost">Disconnect</button>
        </div>
      </div>
    );
  }

  // ----- Top-level screen --------------------------------------------
  function AccountsScreen({ entity }) {
    const [tab, setTab] = React.useState("sources"); // sources | coa
    const sources = window.AKEFIN_DATA.connectedAccounts;
    const visible = sources.filter(s => entity === "all" || s.entity === entity);
    const [selectedId, setSelectedId] = React.useState(visible[0]?.id);
    React.useEffect(() => {
      if (visible.length && !visible.find(s => s.id === selectedId)) {
        setSelectedId(visible[0].id);
      }
    }, [entity]);
    const selected = visible.find(s => s.id === selectedId);

    // Totals (in KRW equivalent)
    const totalKrw = visible.reduce((a, s) => a + window.AKEFIN_DATA.convert(s.balance, s.ccy, "KRW"), 0);
    const okCount  = visible.filter(s => s.status === "ok").length;
    const warnCount = visible.filter(s => s.status === "warn" || s.status === "fail").length;

    return (
      <div className="accounts-screen">
        <div className="screen-head">
          <div>
            <div className="screen-eyebrow">ACCOUNTS · {entity === "all" ? "ALL ENTITIES" : entity.toUpperCase()}</div>
            <h1 className="screen-title">Connected sources</h1>
            <div className="screen-sub">{visible.length} sources · {okCount} healthy · {warnCount} need attention · combined ≈ {fmt(totalKrw, "KRW")}<span className="ccy"> KRW</span></div>
          </div>
          <div className="screen-actions">
            <button className="btn"><Icon name="refresh" size={13} /> Sync all</button>
            <button className="btn primary"><Icon name="import" size={13} /> Connect source</button>
          </div>
        </div>

        <div className="acct-tabs">
          <button className={`acct-tab ${tab === "sources" ? "active" : ""}`} onClick={() => setTab("sources")}>
            CONNECTED SOURCES <span className="acct-tab-count">{visible.length}</span>
          </button>
          <button className={`acct-tab ${tab === "coa" ? "active" : ""}`} onClick={() => setTab("coa")}>
            CHART OF ACCOUNTS
          </button>
        </div>

        {tab === "sources" && (
          <div className="acct-layout">
            <div className="acct-src-grid">
              {visible.map(s => (
                <SourceCard key={s.id} src={s} selected={s.id === selectedId} onClick={() => setSelectedId(s.id)} />
              ))}
            </div>
            <SourceDetail src={selected} />
          </div>
        )}

        {tab === "coa" && <ChartOfAccounts entity={entity} />}
      </div>
    );
  }

  Object.assign(window, { AccountsScreen });
})();
