// home.jsx — Settld Home (4 new balance visualizations:
//   01 constellation · 06 postcards · 07 typographic · 08 feed)

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "balanceViz": "constellation",
  "state": "default"
}/*EDITMODE-END*/;

// ─────────────────────────────────────────────────────────────
// Open balances (drives ledger + viz)
// ─────────────────────────────────────────────────────────────
const DEFAULT_ITEMS = [
  // teal = owed to you
  { id: 'goa',   side: 'teal',  amount: 1280, who: 'Goa Trip',  kind: 'group',  glyph: '✈︎', age: '4d' },
  { id: 'kabir', side: 'teal',  amount: 860,  who: 'Kabir',     kind: 'person',                age: '8d' },
  // coral = you owe
  { id: 'flat',  side: 'coral', amount: 860,  who: 'Flat 2BHK', kind: 'group',  glyph: '⌂',  age: '1d' },
  { id: 'rohan', side: 'coral', amount: 420,  who: 'Rohan',     kind: 'person',                age: '2d' },
];

// Recent-activity events for the FEED viz. Direction:
//   tone: teal | coral | ink | butter — sets dot color
//   dir:  'owed' | 'owe' — colors the inline ₹ amount
const DEFAULT_EVENTS = [
  { id: 'e1', text: 'Priya settled',         amount: 340, dir: 'owed', tone: 'teal',  who: 'Priya', ago: '2h' },
  { id: 'e2', text: 'Flat 2BHK · rent',      amount: 420, dir: 'owe',  tone: 'ink',   glyph: '⌂',  ago: '8h' },
  { id: 'e3', text: 'Kabir nudged you',                                tone: 'coral', who: 'Kabir', ago: '11h' },
];
const NETOWE_EVENTS = [
  { id: 'e1', text: 'Goa Airbnb · 4 ppl',    amount: 1200, dir: 'owe',  tone: 'ink',   glyph: '✈︎', ago: '1h' },
  { id: 'e2', text: 'You paid Priya',         amount: 340,  dir: 'owed', tone: 'teal',  who: 'Priya', ago: '5h' },
  { id: 'e3', text: 'Sunday brunch · 5 ppl',  amount: 280,  dir: 'owe',  tone: 'ink',   glyph: '🍜', ago: '12h' },
];
const SETTLED_EVENTS = [
  { id: 'e1', text: 'Kabir paid you',         amount: 860,  dir: 'owed', tone: 'teal',   who: 'Kabir', ago: '20m' },
  { id: 'e2', text: 'You closed Goa Trip',    amount: 1280, dir: 'owed', tone: 'butter', glyph: '✈︎', ago: '6h' },
];

// Settle strip — owe-first, gentle. Each entry references an open balance.
function settleEntries(items) {
  const coral = items.filter(i => i.side === 'coral');
  const teal  = items.filter(i => i.side === 'teal');
  return [
    coral.sort((a,b) => a.amount - b.amount)[0],
    teal .sort((a,b) => a.amount - b.amount)[0],
  ].filter(Boolean);
}

// ─────────────────────────────────────────────────────────────
// Hero card — each viz fully owns the upper pane.
// ─────────────────────────────────────────────────────────────
function HeroCard({ viz, items, events, owed, owe, allSettled }) {
  const Viz = (
    viz === 'postcards'     ? window.BalancePostcards :
    viz === 'type'          ? window.BalanceTypographic :
    viz === 'feed'          ? window.BalanceFeed :
                              window.BalanceConstellation
  );
  const open = items.length;
  const settle = settleEntries(items);

  return (
    <div className="hero-wrap reveal r1">
      <div className="hero-card">
        <window.SettledConfetti show={allSettled} />

        {/* upper pane — viz owns everything above the dashed divide */}
        <div className="hero-pane">
          <Viz
            items={items}
            events={events}
            owed={owed}
            owe={owe}
            allSettled={allSettled}
          />
        </div>

        <div className="hero-divide" />

        {/* settle strip */}
        <div className="settle-head">
          <span className="settle-eyebrow">settle up</span>
          {!allSettled && <a className="settle-link" href="#">all ({open}) →</a>}
        </div>

        {!allSettled && settle.map((it) => (
          <SettleRow key={it.id} item={it} />
        ))}

        {allSettled && (
          <div
            style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '14px 4px',
              color: 'var(--ink-soft)', fontSize: 14,
            }}
          >
            <span
              style={{
                width: 24, height: 24, borderRadius: 999,
                background: 'var(--butter)', color: 'var(--ink)',
                display: 'grid', placeItems: 'center',
                fontWeight: 700, fontSize: 13,
              }}
            >✓</span>
            nothing to settle. enjoy the chai.
          </div>
        )}
      </div>
    </div>
  );
}

function SettleRow({ item }) {
  const owed = item.side === 'teal';
  const ava = owed
    ? { bg: '#D6EAE2', fg: '#0A5F4F' }
    : { bg: '#FADED4', fg: '#8B3722' };
  const initial = item.who[0];

  return (
    <div className="settle-row">
      <div className="avatar" style={{ background: ava.bg, color: ava.fg }}>{initial}</div>
      <div className="text">
        {owed ? (
          <>
            <strong>{item.who}</strong> owes you{' '}
            <span className="amt teal">₹{item.amount.toLocaleString('en-IN')}</span>
          </>
        ) : (
          <>
            you owe <strong>{item.who}</strong>{' '}
            <span className="amt coral">₹{item.amount.toLocaleString('en-IN')}</span>
          </>
        )}
        <span className="meta">
          {item.glyph && <span className="gly">{item.glyph}</span>}
          <span>{item.age}</span>
        </span>
      </div>
      <button className={owed ? 'pill ghost' : 'pill solid'}>
        {owed ? 'remind' : 'settle'}
      </button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Top bar
// ─────────────────────────────────────────────────────────────
function TopBar() {
  return (
    <div className="topbar">
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div className="logo-mark">S</div>
        <div className="greeting">evening, <strong>Aarav</strong></div>
      </div>
      <div className="me-avatar" title="you">A</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Avatar stack
// ─────────────────────────────────────────────────────────────
const AV_TONES = [
  { bg: '#D6EAE2', fg: '#0A5F4F' },
  { bg: '#FADED4', fg: '#8B3722' },
  { bg: '#F5E4A8', fg: '#6B5208' },
  { bg: '#E8DEC5', fg: '#4A443D' },
];
function AvatarStack({ letters, max = 4 }) {
  const shown = letters.slice(0, max);
  const extra = letters.length - shown.length;
  return (
    <span className="avstack">
      {shown.map((l, i) => {
        const t = AV_TONES[i % AV_TONES.length];
        return (
          <span key={i} className="av" style={{ background: t.bg, color: t.fg }}>{l}</span>
        );
      })}
      {extra > 0 && <span className="av more">+{extra}</span>}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────
// Balances ledger
// ─────────────────────────────────────────────────────────────
function BalancesLedger() {
  return (
    <div className="balances reveal r3">
      <div className="group-block">
        <div className="section-head">
          <span className="section-eyebrow">groups</span>
        </div>
        <div className="ledger-rows">
          <a
            href="Group.html"
            className="ledger-row"
            style={{ textDecoration: 'none', color: 'inherit' }}
          >
            <div className="glyph emoji" aria-hidden="true">⌂</div>
            <div className="body">
              <span className="name">Flat 2BHK</span>
              <span className="sub" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <AvatarStack letters={['A', 'R', 'P']} />
              </span>
            </div>
            <div className="amount coral">you owe ₹860</div>
            <span className="chev">›</span>
          </a>
          <div className="ledger-row">
            <div className="glyph emoji" aria-hidden="true">✈︎</div>
            <div className="body">
              <span className="name">Goa Trip</span>
              <span className="sub" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <AvatarStack letters={['A', 'K', 'P', 'M', 'V']} max={4} />
              </span>
            </div>
            <div className="amount teal">you're owed ₹1,280</div>
            <span className="chev">›</span>
          </div>
        </div>
      </div>

      <div className="group-block">
        <div className="section-head">
          <span className="section-eyebrow">people</span>
        </div>
        <div className="ledger-rows">
          <div className="ledger-row">
            <div className="glyph" style={{ background: '#FADED4', color: '#8B3722' }}>R</div>
            <div className="body">
              <span className="name">Rohan</span>
              <span className="sub">2d</span>
            </div>
            <div className="amount coral">you owe ₹420</div>
            <span className="chev">›</span>
          </div>
          <div className="ledger-row">
            <div className="glyph" style={{ background: '#D6EAE2', color: '#0A5F4F' }}>K</div>
            <div className="body">
              <span className="name">Kabir</span>
              <span className="sub">8d</span>
            </div>
            <div className="amount teal">owes you ₹860</div>
            <span className="chev">›</span>
          </div>
        </div>
      </div>
    </div>
  );
}

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

// ─────────────────────────────────────────────────────────────
// Tweaks panel
// ─────────────────────────────────────────────────────────────
function Tweaks({ t, setTweak }) {
  return (
    <window.TweaksPanel title="Tweaks">
      <window.TweakSection label="balance visualization">
        <window.TweakSelect
          label="style"
          value={t.balanceViz}
          options={[
            { label: '01 · constellation', value: 'constellation' },
            { label: '06 · postcards',     value: 'postcards'     },
            { label: '07 · typographic',   value: 'type'          },
            { label: '08 · feed (since)',  value: 'feed'          },
          ]}
          onChange={(v) => setTweak('balanceViz', v)}
        />
      </window.TweakSection>

      <window.TweakSection label="state">
        <window.TweakRadio
          label="balance"
          value={t.state}
          options={[
            { label: 'default', value: 'default'  },
            { label: 'net owe', value: 'netOwe'   },
            { label: 'settled', value: 'settled'  },
          ]}
          onChange={(v) => setTweak('state', v)}
        />
      </window.TweakSection>
    </window.TweaksPanel>
  );
}

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

  // items & events per state
  let items = DEFAULT_ITEMS;
  let events = DEFAULT_EVENTS;
  if (t.state === 'netOwe') {
    items = [
      { id: 'kabir', side: 'teal',  amount: 740,  who: 'Kabir',     kind: 'person',                age: '8d' },
      { id: 'flat',  side: 'coral', amount: 1480, who: 'Flat 2BHK', kind: 'group',  glyph: '⌂', age: '1d' },
      { id: 'rohan', side: 'coral', amount: 580,  who: 'Rohan',     kind: 'person',                age: '2d' },
      { id: 'goa',   side: 'coral', amount: 320,  who: 'Goa Trip',  kind: 'group',  glyph: '✈︎', age: '4d' },
    ];
    events = NETOWE_EVENTS;
  }
  if (t.state === 'settled') {
    items = [];
    events = SETTLED_EVENTS;
  }

  const owed = items.filter(i => i.side === 'teal' ).reduce((s, i) => s + i.amount, 0);
  const owe  = items.filter(i => i.side === 'coral').reduce((s, i) => s + i.amount, 0);
  const allSettled = items.length === 0;

  const heroKey = `${t.balanceViz}-${t.state}`;

  return (
    <>
      <window.IOSDevice width={390} height={844}>
        <div className="screen">
          <div className="scroller">
            <TopBar />
            <HeroCard
              key={heroKey}
              viz={t.balanceViz}
              items={items}
              events={events}
              owed={owed}
              owe={owe}
              allSettled={allSettled}
            />
            {!allSettled && <BalancesLedger />}
            {allSettled && (
              <div
                className="balances reveal r3"
                style={{
                  padding: '48px 32px 0',
                  textAlign: 'center',
                  color: 'var(--ink-mute)',
                  fontFamily: 'var(--font-mono)',
                  fontSize: 11,
                  letterSpacing: '0.12em',
                  textTransform: 'uppercase',
                }}
              >
                · no open balances ·
              </div>
            )}
          </div>
          <TabBar />
        </div>
      </window.IOSDevice>
      <Tweaks t={t} setTweak={setTweak} />
    </>
  );
}

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