/* Driftwood — app shell: sidebar nav, routing, shared header, Add Entry modal.
   Holds transaction state so Add Entry is genuinely interactive. */

const NAV = [
  { id: "dashboard", label: "Dashboard", icon: "dashboard" },
  { id: "transactions", label: "Transactions", icon: "transactions" },
  { id: "budgets", label: "Budgets", icon: "budgets" },
  { id: "income", label: "Income", icon: "income" },
  { id: "bills", label: "Bills", icon: "bills" },
  { id: "debt", label: "Debt payoff", icon: "debt" },
  { id: "goals", label: "Goals", icon: "goals" },
  { id: "reports", label: "Reports", icon: "reports" },
];

const HOUSEHOLD_KEY = "driftwood.household";

/* ── Household gate — shown on first visit until a code is entered ─────── */
function HouseholdGate({ children }) {
  // sessionStorage is per-tab, so two tabs can hold different household codes simultaneously.
  // localStorage is shared across all tabs on the same URL, which caused cross-household bleed.
  const [code, setCode] = React.useState(() => sessionStorage.getItem(HOUSEHOLD_KEY) || "");
  const [input, setInput] = React.useState("");
  const [err, setErr] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [confirmNew, setConfirmNew] = React.useState(false);

  const acceptCode = (val) => {
    // Clear any stale un-namespaced localStorage keys from before namespacing was added
    Object.keys(localStorage)
      .filter((k) => k.startsWith("driftwood.v1."))
      .forEach((k) => localStorage.removeItem(k));
    sessionStorage.setItem(HOUSEHOLD_KEY, val);
    setCode(val);
  };

  const submit = async () => {
    const val = input.trim().toUpperCase();
    if (!val) { setErr("Please enter your household code."); return; }
    setLoading(true);
    setErr("");
    try {
      const base = window.DRIFTWOOD_API;
      if (base) {
        const r = await fetch(`${base}/verify`, {
          headers: { "Content-Type": "application/json", "X-App-Token": val },
        });
        if (r.ok) {
          const { exists } = await r.json();
          if (!exists) {
            setLoading(false);
            setConfirmNew(true);
            return;
          }
        }
        // Non-ok response or network error: fall through and accept the code
      }
    } catch (e) {
      // Network failure — fall through
    }
    setLoading(false);
    acceptCode(val);
  };

  const confirmSubmit = () => {
    setConfirmNew(false);
    acceptCode(input.trim().toUpperCase());
  };

  if (code) return children;

  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg)" }}>
      <div style={{ width: 380, padding: "40px 36px", background: "var(--surface)", borderRadius: 18, border: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 28 }}>
          <div className="side-mark" style={{ width: 40, height: 40, borderRadius: 12, flexShrink: 0 }}>
            <Icon name="logo" style={{ color: "#fff" }} />
          </div>
          <div>
            <div style={{ fontWeight: 700, fontSize: 17, color: "var(--text)" }}>Driftwood</div>
            <div className="sub" style={{ fontSize: 12 }}>Shared planning for two</div>
          </div>
        </div>

        <div style={{ fontWeight: 600, fontSize: 15, color: "var(--text)", marginBottom: 6 }}>
          Enter your household code
        </div>
        <div className="sub" style={{ fontSize: 13, marginBottom: 20, lineHeight: 1.5 }}>
          Your code keeps your data separate from other households using this app.
          Ask the person who set it up if you don't know yours.
        </div>

        <div className="field" style={{ marginBottom: 16 }}>
          <div className="input">
            <input
              value={input}
              onChange={(e) => { setInput(e.target.value.toUpperCase()); setErr(""); setConfirmNew(false); }}
              onKeyDown={(e) => e.key === "Enter" && !loading && submit()}
              placeholder="e.g. XXX-YYY"
              autoFocus
              disabled={loading}
              style={{ fontSize: 16, fontWeight: 600, letterSpacing: "0.06em" }}
            />
          </div>
          {err && <div style={{ color: "var(--neg)", fontSize: 12, marginTop: 6 }}>{err}</div>}
        </div>

        {confirmNew && (
          <div style={{ background: "var(--panel2)", borderRadius: 12, padding: "14px 16px", marginBottom: 16, fontSize: 13.5, color: "var(--mid)", lineHeight: 1.5 }}>
            No household found for <b style={{ color: "var(--hi)" }}>{input.trim().toUpperCase()}</b>. Start a new one?
            <div style={{ display: "flex", gap: 10, marginTop: 12 }}>
              <button className="btn btn-primary" style={{ flex: 1 }} onClick={confirmSubmit}>Yes, start fresh</button>
              <button className="btn btn-ghost" onClick={() => setConfirmNew(false)}>Cancel</button>
            </div>
          </div>
        )}

        {!confirmNew && (
          <button className="btn btn-primary" style={{ width: "100%", fontSize: 15 }} onClick={submit} disabled={loading}>
            {loading ? "Checking…" : "Open my household →"}
          </button>
        )}
      </div>
    </div>
  );
}

function ScreenHeader({ title, sub, children }) {
  return (
    <div className="topbar">
      <div>
        <h1>{title}</h1>
        {sub && <div className="sub">{sub}</div>}
      </div>
      <div className="topbar-right">{children}</div>
    </div>
  );
}

function AddEntryModal({ onClose, onAdd }) {
  const cats = ["Groceries", "Dining out", "Transportation", "Utilities", "Shopping", "Health", "Subscription", "Income"];
  const names = window.useMemberNames();
  const [form, setForm] = React.useState({ merchant: "", amount: "", cat: "Groceries", who: names[0] || "Maya", type: "expense" });
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const submit = () => {
    const amt = parseFloat(form.amount) || 0;
    if (!form.merchant || !amt) { onClose(); return; }
    onAdd({
      date: "May 30", merchant: form.merchant, cat: form.type === "income" ? "Income" : form.cat,
      who: form.who, amount: form.type === "income" ? Math.abs(amt) : -Math.abs(amt),
      color: form.type === "income" ? "green" : "teal",
    });
    onClose();
  };
  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <h2>Add entry</h2>
        <p className="sub">Log a transaction for your shared tracker.</p>
        <div className="field" style={{ marginBottom: 14 }}>
          <div className="segctl">
            <button className={form.type === "expense" ? "on" : ""} onClick={() => setForm({ ...form, type: "expense" })}>Expense</button>
            <button className={form.type === "income" ? "on" : ""} onClick={() => setForm({ ...form, type: "income" })}>Income</button>
          </div>
        </div>
        <div className="field" style={{ marginBottom: 14 }}>
          <label>Description</label>
          <div className="input"><input value={form.merchant} onChange={set("merchant")} placeholder="e.g. Whole Foods" style={{ fontSize: 15, fontWeight: 500 }} /></div>
        </div>
        <div className="modal-row">
          <div className="field">
            <label>Amount</label>
            <div className="input"><span className="pre">$</span><input value={form.amount} onChange={set("amount")} placeholder="0.00" inputMode="decimal" /></div>
          </div>
          <div className="field">
            <label>Who</label>
            <div className="input"><select value={form.who} onChange={set("who")}>{names.map((n) => <option key={n} value={n}>{n}</option>)}</select></div>
          </div>
        </div>
        {form.type === "expense" && (
          <div className="field">
            <label>Category</label>
            <div className="input"><select value={form.cat} onChange={set("cat")}>{cats.filter((c) => c !== "Income").map((c) => <option key={c}>{c}</option>)}</select></div>
          </div>
        )}
        <div className="modal-foot">
          <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" onClick={submit}>Add entry</button>
        </div>
      </div>
    </div>
  );
}

function App() {
  const household = sessionStorage.getItem(HOUSEHOLD_KEY) || "";
  const [screen, setScreen] = React.useState(() => localStorage.getItem("fp.screen") || "dashboard");
  const [addOpen, setAddOpen] = React.useState(false);
  const [txns, setTxns] = window.usePersist("transactions", window.FP.transactions);

  React.useEffect(() => { localStorage.setItem("fp.screen", screen); }, [screen]);
  const nav = (id) => setScreen(id);
  const addTxn = (tx) => setTxns((t) => [tx, ...t]);

  const switchHousehold = () => {
    if (confirm("Switch to a different household? This will clear your local data on this device.")) {
      sessionStorage.removeItem(HOUSEHOLD_KEY);
      localStorage.removeItem("fp.screen");
      location.reload();
    }
  };

  const screens = {
    dashboard: window.ScreenDashboard, transactions: window.ScreenTransactions,
    budgets: window.ScreenBudgets, income: window.ScreenIncome, bills: window.ScreenBills,
    debt: window.ScreenDebt, goals: window.ScreenGoals, reports: window.ScreenReports,
  };
  const Screen = screens[screen] || (() => <div style={{ padding: 40 }}>Coming soon</div>);

  return (
    <HouseholdGate>
      <div className="app">
        <aside className="side">
          <div className="side-brand">
            <div className="side-mark"><Icon name="logo" style={{ color: "#fff" }} /></div>
            <div>
              <div className="side-brand-name">Driftwood</div>
              <div className="side-brand-sub">Shared planning for two</div>
            </div>
          </div>
          <nav className="side-nav">
            {NAV.map((n) => (
              <button key={n.id} className={"side-link" + (screen === n.id ? " on" : "")} onClick={() => nav(n.id)}>
                <Icon name={n.icon} /> {n.label}
              </button>
            ))}
          </nav>
          <div className="side-foot">
            <span className="dotpulse" />
            <span style={{ fontWeight: 600, letterSpacing: "0.04em" }}>{household}</span>
            <button className="reset-link" title="Switch household" onClick={switchHousehold}>Switch</button>
          </div>
          <div className="side-foot" style={{ paddingTop: 0, borderTop: "none" }}>
            <button className="reset-link" style={{ marginLeft: 0, fontSize: 11 }} title="Clear saved data and reload"
              onClick={() => { if (confirm("Reset all data back to the sample numbers? This clears your saved budgets, bills, debts, goals and income.")) { window.clearStored(); localStorage.removeItem("fp.screen"); location.reload(); } }}>Reset data</button>
          </div>
        </aside>

        <main className="main">
          <div className="fadein" key={screen}>
            <Screen nav={nav} openAdd={() => setAddOpen(true)} txns={txns} addTxn={addTxn} setTxns={setTxns} />
          </div>
        </main>

        {addOpen && <AddEntryModal onClose={() => setAddOpen(false)} onAdd={addTxn} />}
      </div>
    </HouseholdGate>
  );
}

Object.assign(window, { ScreenHeader, App });
