// claude-group.jsx — Settld group screen, redesigned.
// Thesis: separated affordances (settings ≠ card tap), one balance hero number,
// one deliberate "settle" primary action, segmented transactions/balances toggle,
// pending state surfaced clearly, FAB for add expense. No radial/long-press.

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

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

// ─── Data ──────────────────────────────────────────────────────────────────
const MEMBERS = [
  { key: 'A', name: 'Aarav',  tone: { bg: '#D6EAE2', fg: '#0A5F4F' }, isYou: true },
  { key: 'R', name: 'Rohan',  tone: { bg: '#FADED4', fg: '#8B3722' } },
  { key: 'P', name: 'Priya',  tone: { bg: '#F5E4A8', fg: '#6B5208' } },
];
const toneOf = (name) => MEMBERS.find(m => m.name === name)?.tone || { bg: '#E8DEC5', fg: '#4A443D' };

const GROUP = { emoji: '⌂', name: 'Flat 2BHK', age: '8 mo', members: MEMBERS.length };

const TXNS = [
  { day: 'Today', items: [
    { id: 'gro', title: 'Groceries — Big Basket', cat: '🛒',
      payer: 'Rohan', participants: ['Aarav', 'Rohan', 'Priya'],
      gross: 1240, myShare: { side: 'coral', amt: 413 } },
  ]},
  { day: 'Yesterday', items: [
    { id: 'net', title: 'Internet bill — Airtel', cat: '📶',
      payer: 'Aarav', participants: ['Aarav', 'Rohan', 'Priya'],
      gross: 999, myShare: { side: 'teal', amt: 666 } },
  ]},
  { day: '3 days ago', items: [
    { id: 'mnt', title: 'Building maintenance', cat: '🔧',
      payer: 'Priya', participants: ['Aarav', 'Rohan', 'Priya'],
      gross: 600, myShare: { side: 'coral', amt: 200 } },
    { id: 'sun', title: 'Sunday brunch', cat: '🥞',
      payer: 'Rohan', participants: ['Aarav', 'Rohan', 'Priya'],
      gross: 1800, myShare: { side: 'coral', amt: 600 } },
  ]},
  { day: 'Last week', items: [
    { id: 'chai', title: 'Morning chai run', cat: '🍵',
      payer: 'Aarav', participants: ['Aarav', 'Rohan', 'Priya'],
      gross: 120, myShare: { side: 'teal', amt: 80 } },
  ]},
];

const FLOWS = [
  { id: 'a-r', from: 'Aarav', to: 'Rohan', amount: 680, note: '2 expenses' },
  { id: 'a-p', from: 'Aarav', to: 'Priya', amount: 180, note: 'net of internet' },
];

const NET_OWE = 860;

// ─── Top nav ───────────────────────────────────────────────────────────────
function TopNav({ onSettings }) {
  return (
    <div className="cg-topnav">
      <a className="cg-nav-icon" href="Home.html" aria-label="back to home">
        <svg width="8" height="14" viewBox="0 0 8 14" fill="none" aria-hidden="true">
          <path d="M7 1L1 7L7 13" stroke="currentColor" strokeWidth="1.6"
            strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </a>
      <span className="cg-nav-title">{GROUP.name}</span>
      <button className="cg-nav-icon" aria-label="settings" onClick={onSettings}>
        <svg width="16" height="4" viewBox="0 0 16 4" fill="none" aria-hidden="true">
          <circle cx="2" cy="2" r="1.5" fill="currentColor" />
          <circle cx="8" cy="2" r="1.5" fill="currentColor" />
          <circle cx="14" cy="2" r="1.5" fill="currentColor" />
        </svg>
      </button>
    </div>
  );
}

// ─── Group header card ─────────────────────────────────────────────────────
function GroupHeader({ state, onSettle }) {
  const isPending = state === 'pending';
  const isSettled = state === 'settled';

  return (
    <div className="cg-header c-reveal r1">
      {/* Group identity row */}
      <div className="cg-group-row">
        <div className="cg-group-emoji">{GROUP.emoji}</div>
        <div className="cg-group-info">
          <div className="cg-group-name">{GROUP.name}</div>
          <div className="cg-group-meta">{GROUP.members} members · {GROUP.age}</div>
        </div>
        <div className="cg-avatars">
          {MEMBERS.map((m) => (
            <div key={m.key} className="cg-av-sm"
              style={{ background: m.tone.bg, color: m.tone.fg }}
              title={m.name}>
              {m.key}
            </div>
          ))}
        </div>
      </div>

      {/* Balance hero */}
      <div className="cg-balance-eyebrow">
        {isSettled ? 'all settled up' : 'you owe this group'}
      </div>
      {isSettled ? (
        <div className="cg-balance-num teal">
          <span className="cur">₹</span>0
        </div>
      ) : (
        <div className="cg-balance-num coral">
          <span className="cur">₹</span>{rupee(NET_OWE)}
        </div>
      )}
      <div className="cg-balance-desc">
        {isSettled
          ? 'Nothing open. Enjoy the chai.'
          : (isPending
            ? 'Rohan flow pending · waiting for confirmation'
            : 'pay Rohan ₹680 · pay Priya ₹180')}
      </div>

      {/* Primary action */}
      {isSettled ? (
        <div className="cg-settled-badge">
          <span>✓</span>
          <span>all settled up</span>
        </div>
      ) : (
        <button
          className={isPending ? 'cg-settle-btn pending-state' : 'cg-settle-btn'}
          onClick={isPending ? undefined : onSettle}
          disabled={isPending}
          aria-label={isPending ? 'Pending confirmation from Rohan' : 'Settle ₹680 with Rohan'}>
          {isPending ? (
            <>
              <span className="c-pending-dot" />
              <span>waiting for Rohan to confirm</span>
            </>
          ) : (
            <>
              <span>settle ₹680 → Rohan</span>
              <span aria-hidden="true">→</span>
            </>
          )}
        </button>
      )}
    </div>
  );
}

// ─── Segmented toggle ──────────────────────────────────────────────────────
function SegToggle({ view, onChange }) {
  const tabs = [
    { id: 'transactions', label: 'Transactions' },
    { id: 'balances',     label: 'Balances'     },
  ];
  const activeIdx = tabs.findIndex(t => t.id === view);
  return (
    <div className="cg-seg-wrap c-reveal r2">
      <div className="cg-seg" role="tablist">
        {tabs.map((tab) => (
          <button key={tab.id}
            className={view === tab.id ? 'cg-seg-btn active' : 'cg-seg-btn'}
            role="tab"
            aria-selected={view === tab.id}
            onClick={() => onChange(tab.id)}>
            {tab.label}
          </button>
        ))}
        <div className="cg-seg-thumb" style={{
          left: `calc(${activeIdx} * 50% + 3px)`,
          width: 'calc(50% - 6px)',
        }} />
      </div>
    </div>
  );
}

// ─── Transaction pane ──────────────────────────────────────────────────────
function TxnRow({ txn, swipedId, onSwipe, onEdit, onDelete }) {
  const isSwiped = swipedId === txn.id;
  const isYouPayer = txn.payer === 'Aarav';
  return (
    <div className={isSwiped ? 'cg-txn-row swiped' : 'cg-txn-row'}
      onClick={() => onSwipe(isSwiped ? null : txn.id)}>
      <div className="cg-txn-avatar">{txn.cat}</div>
      <div className="cg-txn-body">
        <div className="cg-txn-title">{txn.title}</div>
        <div className="cg-txn-meta">
          <div className="cg-split-avs">
            {txn.participants.map(p => {
              const t = toneOf(p);
              return (
                <div key={p} className="cg-split-av"
                  style={{ background: t.bg, color: t.fg }}
                  title={p}>
                  {p[0]}
                </div>
              );
            })}
          </div>
          <span>{isYouPayer ? 'you paid' : txn.payer + ' paid'}</span>
        </div>
      </div>
      <div className="cg-txn-right">
        <span className="cg-txn-gross">₹{rupee(txn.gross)}</span>
        <span className={`cg-txn-share ${txn.myShare.side}`}>
          {txn.myShare.side === 'coral' ? '−' : '+'}₹{rupee(txn.myShare.amt)}
        </span>
      </div>
      {isSwiped && (
        <div className="cg-txn-actions">
          <button className="cg-action-btn edit"
            onClick={(e) => { e.stopPropagation(); onEdit(txn); }}>edit</button>
          <button className="cg-action-btn del"
            onClick={(e) => { e.stopPropagation(); onDelete(txn); }}>delete</button>
        </div>
      )}
    </div>
  );
}

function TxnPane({ state, toast }) {
  const [swipedId, setSwipedId] = React.useState(null);
  const onEdit  = (txn) => toast('Editing "' + txn.title + '"…');
  const onDelete = (txn) => toast('"' + txn.title + '" deleted');

  const hasPending = state === 'pending';

  return (
    <div className="c-reveal r3">
      {hasPending && (
        <div className="c-section" style={{ marginTop: 0, marginBottom: 16 }}>
          <div className="c-section-head">
            <span className="c-section-eyebrow">pending confirmation</span>
            <span className="c-section-count">1</span>
          </div>
          <div className="c-list">
            <div className="cg-pending-row">
              <div className="c-av" style={{ background: '#FADED4', color: '#8B3722' }}>R</div>
              <div className="c-row-body">
                <span className="c-row-line">
                  you paid <strong>Rohan</strong>{' '}
                  <span className="amt">₹680</span>
                </span>
                <span className="c-row-meta">
                  <span className="c-pending-dot" />
                  <span>waiting for Rohan to confirm · just now</span>
                </span>
              </div>
              <button className="c-pill pending">pending</button>
            </div>
          </div>
        </div>
      )}
      {TXNS.map((group, gi) => (
        <div key={group.day} className="cg-day-group c-section" style={{ marginTop: gi === 0 ? 0 : 20 }}>
          <div className="c-section-head">
            <span className="cg-day-label">{group.day}</span>
          </div>
          <div className="c-list">
            {group.items.map(txn => (
              <TxnRow key={txn.id} txn={txn}
                swipedId={swipedId} onSwipe={setSwipedId}
                onEdit={onEdit} onDelete={onDelete} />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

// ─── Balances pane ─────────────────────────────────────────────────────────
function FlowRow({ flow, state, onSettle, toast }) {
  const isPending = state === 'pending' && flow.id === 'a-r';
  const toTone = toneOf(flow.to);
  const isYouFrom = flow.from === 'Aarav';
  return (
    <div className="cg-flow-row">
      <div className="c-av" style={{ background: toTone.bg, color: toTone.fg }}>
        {flow.to[0]}
      </div>
      <div className="cg-flow-body">
        <span className="cg-flow-line">
          {isYouFrom ? 'you pay' : flow.from + ' pays'}{' '}
          <strong>{flow.to}</strong>{' '}
          <span className={`amt ${isYouFrom ? 'coral' : 'teal'}`}>
            ₹{rupee(flow.amount)}
          </span>
        </span>
        <span className="cg-flow-note">{flow.note}</span>
      </div>
      <div className="cg-flow-pills">
        {isPending ? (
          <button className="c-pill pending">pending</button>
        ) : isYouFrom ? (
          <button className="c-pill solid" onClick={() => onSettle(flow)}>settle</button>
        ) : (
          <button className="c-pill ghost" onClick={() => toast('Nudged ' + flow.from + ' — warmly.')}>remind</button>
        )}
      </div>
    </div>
  );
}

function BalancesPane({ state, onSettle, toast }) {
  return (
    <div className="c-reveal r3">
      <div className="c-section" style={{ marginTop: 0 }}>
        <div className="c-section-head">
          <span className="c-section-eyebrow">fewest payments</span>
          <span className="c-section-count">{FLOWS.length}</span>
        </div>
        <div className="c-list">
          {FLOWS.map(flow => (
            <FlowRow key={flow.id} flow={flow} state={state}
              onSettle={onSettle} toast={toast} />
          ))}
          <div className="cg-net-footer">
            <span className="cg-net-label">your net position</span>
            <span className="cg-net-amount coral">−₹{rupee(NET_OWE)}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Confirm sheet (settle) ────────────────────────────────────────────────
function SettleSheet({ 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}</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} 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>
    </>
  );
}

// ─── Settings sheet ────────────────────────────────────────────────────────
function SettingsSheet({ show, onClose, toast }) {
  return (
    <>
      <div className={`c-sheet-scrim ${show ? 'show' : ''}`} onClick={onClose} />
      <div className={`c-sheet ${show ? 'show' : ''}`}>
        <div className="c-sheet-grab" />
        <h3>Flat 2BHK</h3>
        <div style={{ marginTop: 16 }}>
          <div className="cg-settings-section-label">group</div>
          <div className="cg-settings-row">
            <span className="cg-settings-label">Members</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div className="cg-avatars">
                {MEMBERS.map(m => (
                  <div key={m.key} className="cg-av-sm"
                    style={{ background: m.tone.bg, color: m.tone.fg }}>
                    {m.key}
                  </div>
                ))}
              </div>
              <button className="cg-settings-action"
                onClick={() => { onClose(); toast('Invite link copied.'); }}>
                invite
              </button>
            </div>
          </div>
          <div className="cg-settings-row">
            <span className="cg-settings-label">Simplify debts</span>
            <span className="cg-settings-value">on</span>
          </div>
          <div className="cg-settings-row">
            <span className="cg-settings-label">Created</span>
            <span className="cg-settings-value">8 mo ago</span>
          </div>
          <div className="cg-settings-section-label">danger zone</div>
          <div className="cg-settings-row">
            <span className="cg-settings-label">Leave group</span>
            <button className="cg-settings-action danger"
              onClick={() => { onClose(); toast('Not going anywhere just yet.'); }}>
              leave
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

// ─── Tab bar ───────────────────────────────────────────────────────────────
function TabBar({ onAdd }) {
  return (
    <div className="c-tabbar">
      <div className="c-tabrow">
        <a className="c-tab" href="Home.html"><div className="glyph">⌂</div><div className="lbl">home</div></a>
        <div className="c-tab active"><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="view">
        <window.TweakRadio
          label="view"
          value={t.view}
          options={[
            { label: 'transactions', value: 'transactions' },
            { label: 'balances',     value: 'balances'     },
          ]}
          onChange={(v) => setTweak('view', v)}
        />
      </window.TweakSection>
      <window.TweakSection label="state">
        <window.TweakRadio
          label="state"
          value={t.state}
          options={[
            { label: 'active',  value: 'active'  },
            { label: 'pending', value: 'pending' },
            { label: 'settled', value: 'settled' },
          ]}
          onChange={(v) => setTweak('state', v)}
        />
      </window.TweakSection>
    </window.TweaksPanel>
  );
}

// ─── Root ──────────────────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  // local view state — tweak seeds it, segmented toggle drives it
  const [view, setView] = React.useState(t.view);
  React.useEffect(() => { setView(t.view); }, [t.view]);

  const [sheet, setSheet] = React.useState(null);
  const [settingsOpen, setSettingsOpen] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const [localState, setLocalState] = React.useState(t.state);

  // reset local state when tweak changes
  React.useEffect(() => { setLocalState(t.state); setSheet(null); }, [t.state]);

  // toast auto-dismiss
  React.useEffect(() => {
    if (!toast) return;
    const id = setTimeout(() => setToast(null), 2400);
    return () => clearTimeout(id);
  }, [toast]);

  const fireToast = (msg) => setToast(msg);

  const onSettle = (item) => {
    // settle button in header opens sheet for the primary flow (Rohan ₹680)
    setSheet({ to: 'Rohan', amount: 680, id: 'a-r' });
  };

  const onFlowSettle = (flow) => {
    setSheet({ to: flow.to, amount: flow.amount, id: flow.id });
  };

  const onConfirm = (item) => {
    setSheet(null);
    setLocalState('pending');
    fireToast('Opening UPI app to pay ' + item.to + ' →');
  };

  const onAdd = () => fireToast('＋ add expense');

  return (
    <>
      <window.IOSDevice width={390} height={844}>
        <div className="screen">
          <div className="scroller">
            <TopNav onSettings={() => setSettingsOpen(true)} />
            <GroupHeader state={localState} onSettle={onSettle} />
            <SegToggle view={view} onChange={setView} />
            {view === 'transactions'
              ? <TxnPane state={localState} toast={fireToast} />
              : <BalancesPane state={localState} onSettle={onFlowSettle} toast={fireToast} />}
            <div style={{ height: 24 }} />
          </div>
          <SettleSheet item={sheet} onClose={() => setSheet(null)} onConfirm={onConfirm} />
          <SettingsSheet show={settingsOpen} onClose={() => setSettingsOpen(false)} toast={fireToast} />
          <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 />);
