// claude-home.jsx — Settld home, redesigned.
// Thesis: the home is a WORKLIST, not a dashboard. One number is the hero
// (PCD §7 "numbers are the hero"); below it sits the only thing that matters —
// who to settle and who to nudge. Settling is deliberate and honours the
// real two-party confirm-receipt model (flows/07): tapping settle opens a
// confirm, hands off to UPI, then the balance becomes *pending* until the
// payee confirms. Confetti is deferred to that confirmation, never fired on
// the payer's tap. The first real session is a designed state, not a void
// (PCD §6.2 "zero cold starts").

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "state": "active"
}/*EDITMODE-END*/;

const rupee = (n) => n.toLocaleString('en-IN');

// ── data per state ───────────────────────────────────────────────
const ACTIVE = {
  owe:  [
    { id: 'flat',  who: 'Flat 2BHK', kind: 'group',  glyph: '⌂', amount: 860, age: '1d', to: 'Priya' },
    { id: 'rohan', who: 'Rohan',     kind: 'person',             amount: 420, age: '2d', to: 'Rohan' },
  ],
  owed: [
    { id: 'goa',   who: 'Goa Trip',  kind: 'group',  glyph: '✈︎', amount: 1280, age: '4d' },
    { id: 'kabir', who: 'Kabir',     kind: 'person',             amount: 860,  age: '8d' },
  ],
  pending: [],
};
const PENDING = {
  owe:  [{ id: 'rohan', who: 'Rohan', kind: 'person', amount: 420, age: '2d', to: 'Rohan' }],
  owed: [{ id: 'kabir', who: 'Kabir', kind: 'person', amount: 860, age: '8d' }],
  pending: [{ id: 'priya', who: 'Priya', amount: 860, since: 'just now' }],
};

function netOf(d) {
  const owed = d.owed.reduce((s, i) => s + i.amount, 0);
  const owe  = d.owe.reduce((s, i) => s + i.amount, 0);
  return { owed, owe, net: owed - owe };
}

const AV = {
  teal:  { bg: '#D6EAE2', fg: '#0A5F4F' },
  coral: { bg: '#FADED4', fg: '#8B3722' },
  butter:{ bg: '#F5E4A8', fg: '#6B5208' },
};

// ── Top bar ───────────────────────────────────────────────────────
function TopBar() {
  return (
    <div className="c-topbar">
      <div className="c-brand">
        <div className="c-logo">S</div>
        <div className="c-greeting">evening, <strong>Aarav</strong></div>
      </div>
      <div className="c-me" title="you">A</div>
    </div>
  );
}

// ── Hero: the one number ───────────────────────────────────────────
function Hero({ data }) {
  const { owed, owe, net } = netOf(data);
  const open = data.owe.length + data.owed.length;
  const ahead = net >= 0;
  return (
    <div className="c-hero c-reveal r1">
      <div className="c-hero-eyebrow">{ahead ? "you're ahead by" : "you're behind by"}</div>
      <div className={`c-hero-net ${ahead ? 'teal' : 'coral'}`}>
        <span className="cur">₹</span>{rupee(Math.abs(net))}
      </div>
      <div className="c-hero-sub">
        owed <span className="amt teal">₹{rupee(owed)}</span>
        {'  ·  '}
        owe <span className="amt coral">₹{rupee(owe)}</span>
      </div>
      <div className="c-hero-rule" />
      <div className="c-hero-foot">
        <span>{open} open · {data.pending.length} pending</span>
        <a href="#">breakdown →</a>
      </div>
    </div>
  );
}

// ── Worklist rows ──────────────────────────────────────────────────
function SettleRow({ item, onSettle }) {
  const t = AV.coral;
  return (
    <div className="c-row">
      {item.kind === 'group'
        ? <div className="c-av emoji">{item.glyph}</div>
        : <div className="c-av" style={{ background: t.bg, color: t.fg }}>{item.who[0]}</div>}
      <div className="c-row-body">
        <span className="c-row-line">
          you owe <strong>{item.who}</strong> <span className="amt coral">₹{rupee(item.amount)}</span>
        </span>
        <span className="c-row-meta"><span>{item.age}</span></span>
      </div>
      <button className="c-pill solid" onClick={() => onSettle(item)}>settle</button>
    </div>
  );
}

function CollectRow({ item, onRemind }) {
  const t = AV.teal;
  return (
    <div className="c-row">
      {item.kind === 'group'
        ? <div className="c-av emoji">{item.glyph}</div>
        : <div className="c-av" style={{ background: t.bg, color: t.fg }}>{item.who[0]}</div>}
      <div className="c-row-body">
        <span className="c-row-line">
          <strong>{item.who}</strong> owes you <span className="amt teal">₹{rupee(item.amount)}</span>
        </span>
        <span className="c-row-meta"><span>{item.age}</span></span>
      </div>
      <button className="c-pill ghost" onClick={() => onRemind(item)}>remind</button>
    </div>
  );
}

function PendingRow({ item }) {
  const t = AV.butter;
  return (
    <div className="c-row">
      <div className="c-av" style={{ background: t.bg, color: t.fg }}>{item.who[0]}</div>
      <div className="c-row-body">
        <span className="c-row-line">
          you paid <strong>{item.who}</strong> <span className="amt">₹{rupee(item.amount)}</span>
        </span>
        <span className="c-row-meta">
          <span className="c-pending-dot" /> waiting for {item.who} to confirm · {item.since}
        </span>
      </div>
      <button className="c-pill pending">pending</button>
    </div>
  );
}

// ── First-run (zero cold start) ────────────────────────────────────
function FirstRun({ onAdd }) {
  return (
    <div className="c-firstrun c-reveal r1">
      <h2>One group, one split.<br/>You're already set up.</h2>
      <p>We started <strong>Flat 2BHK</strong> with Rohan and Priya from your invite. Add the first expense and watch it split.</p>
      <button className="chip" onClick={onAdd} style={{ cursor: 'pointer', width: '100%', textAlign: 'left' }}>
        <span style={{ fontSize: 18 }}>＋</span>
        <span>Add your first expense — even the ₹40 chai counts.</span>
      </button>
    </div>
  );
}

// ── Settled (deferred celebration) ─────────────────────────────────
function Settled({ confetti }) {
  return (
    <div className="c-settled-wrap c-reveal r1">
      {confetti && <window.SettledConfetti show={true} />}
      <div className="c-settled-badge">✓</div>
      <h2>All settled up.</h2>
      <p>nothing open. enjoy the chai.</p>
    </div>
  );
}

// ── Confirm sheet (deliberate settle) ──────────────────────────────
function ConfirmSheet({ item, onClose, onConfirm }) {
  const show = !!item;
  return (
    <>
      <div className={`c-sheet-scrim ${show ? 'show' : ''}`} onClick={onClose} />
      <div className={`c-sheet ${show ? 'show' : ''}`}>
        <div className="c-sheet-grab" />
        {item && (
          <>
            <h3>Settle with {item.to || item.who}</h3>
            <p className="lede">Opens your UPI app to pay. We don't move the money — you do.</p>
            <div className="pay-amt"><span className="cur">₹</span>{rupee(item.amount)}</div>
            <div className="c-sheet-note">
              <span style={{ fontSize: 14, lineHeight: 1 }}>ⓘ</span>
              <span>Marked settled only once {item.to || item.who} confirms they got it. Until then it shows as pending.</span>
            </div>
            <div className="c-sheet-actions">
              <button className="c-btn secondary" onClick={onClose}>cancel</button>
              <button className="c-btn primary" onClick={() => onConfirm(item)}>
                <span>open UPI app</span><span aria-hidden="true">→</span>
              </button>
            </div>
          </>
        )}
      </div>
    </>
  );
}

// ── Tab bar ─────────────────────────────────────────────────────────
function TabBar({ onAdd }) {
  return (
    <div className="c-tabbar">
      <div className="c-tabrow">
        <div className="c-tab active"><div className="glyph">⌂</div><div className="lbl">home</div></div>
        <div className="c-tab"><div className="glyph">◦◦</div><div className="lbl">groups</div></div>
        <div className="c-tab add"><div className="add-btn" aria-label="add expense" onClick={onAdd}>＋</div></div>
        <div className="c-tab"><div className="glyph">≡</div><div className="lbl">activity</div></div>
        <div className="c-tab"><div className="glyph">A</div><div className="lbl">you</div></div>
      </div>
    </div>
  );
}

// ── Tweaks ──────────────────────────────────────────────────────────
function Tweaks({ t, setTweak }) {
  return (
    <window.TweaksPanel title="Tweaks">
      <window.TweakSection label="home state">
        <window.TweakRadio
          label="state"
          value={t.state}
          options={[
            { label: 'active',   value: 'active'   },
            { label: 'pending',  value: 'pending'  },
            { label: 'first run',value: 'firstRun' },
            { label: 'settled',  value: 'settled'  },
          ]}
          onChange={(v) => setTweak('state', v)}
        />
      </window.TweakSection>
    </window.TweaksPanel>
  );
}

// ── Root ────────────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const base = t.state === 'pending' ? PENDING : ACTIVE;

  // live settle interaction — a settled row moves into `pending`
  const [pendingExtra, setPendingExtra] = React.useState([]);
  const [settledIds, setSettledIds] = React.useState([]);
  const [sheet, setSheet] = React.useState(null);
  const [toast, setToast] = React.useState(null);
  React.useEffect(() => { setPendingExtra([]); setSettledIds([]); }, [t.state]);
  React.useEffect(() => {
    if (!toast) return;
    const id = setTimeout(() => setToast(null), 2200);
    return () => clearTimeout(id);
  }, [toast]);

  const fireToast = (msg) => setToast(msg);
  const onSettle = (item) => setSheet(item);
  const onConfirm = (item) => {
    setSheet(null);
    setSettledIds((p) => [...p, item.id]);
    setPendingExtra((p) => [...p, { id: `p-${item.id}`, who: item.to || item.who, amount: item.amount, since: 'just now' }]);
    fireToast(`Opening UPI app to pay ${item.to || item.who} →`);
  };
  const onRemind = (item) => fireToast(`Nudged ${item.who} — warmly, never naggy.`);
  const onAdd = () => fireToast('＋ add expense');

  const owe = base.owe.filter((i) => !settledIds.includes(i.id));
  const owed = base.owed;
  const pending = [...base.pending, ...pendingExtra];

  let body;
  if (t.state === 'firstRun') {
    body = <FirstRun onAdd={onAdd} />;
  } else if (t.state === 'settled') {
    body = <Settled confetti={true} />;
  } else {
    body = (
      <>
        <Hero data={{ owe, owed, pending }} />
        {owe.length > 0 && (
          <div className="c-section c-reveal r2">
            <div className="c-section-head">
              <span className="c-section-eyebrow">to settle</span>
              <span className="c-section-count">{owe.length}</span>
            </div>
            <div className="c-list">
              {owe.map((it) => <SettleRow key={it.id} item={it} onSettle={onSettle} />)}
            </div>
          </div>
        )}
        {pending.length > 0 && (
          <div className="c-section c-reveal r3">
            <div className="c-section-head">
              <span className="c-section-eyebrow">pending confirmation</span>
              <span className="c-section-count">{pending.length}</span>
            </div>
            <div className="c-list">
              {pending.map((it) => <PendingRow key={it.id} item={it} />)}
            </div>
          </div>
        )}
        {owed.length > 0 && (
          <div className="c-section c-reveal r4">
            <div className="c-section-head">
              <span className="c-section-eyebrow">to collect</span>
              <span className="c-section-count">{owed.length}</span>
            </div>
            <div className="c-list">
              {owed.map((it) => <CollectRow key={it.id} item={it} onRemind={onRemind} />)}
            </div>
          </div>
        )}
      </>
    );
  }

  return (
    <>
      <window.IOSDevice width={390} height={844}>
        <div className="screen">
          <div className="scroller">
            <TopBar />
            {body}
            <div style={{ height: 24 }} />
          </div>
          <ConfirmSheet item={sheet} onClose={() => setSheet(null)} onConfirm={onConfirm} />
          <div className={`c-toast ${toast ? 'show' : ''}`}>{toast}</div>
          <TabBar onAdd={onAdd} />
        </div>
      </window.IOSDevice>
      <Tweaks t={t} setTweak={setTweak} />
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
