// app-mobile.jsx — iPhone version of Twogether

const { useState: useM } = React;

const MobilePhone = ({ density, life, scenario }) => {
  const [tab, setTab] = useM('home');
  const [activeUser, setActiveUser] = useM('B');

  return (
    <div style={{
      width: '100%', height: '100%',
      background: '#fbfaf7', display: 'flex', flexDirection: 'column',
      fontFamily: 'Inter, system-ui',
    }}>
      {/* Top bar w/ user switcher */}
      <div style={{
        padding: '6px 18px 10px', display: 'flex', alignItems: 'center', gap: 10,
        background: '#fbfaf7',
      }}>
        <div style={{
          width: 26, height: 26, borderRadius: 7,
          background: 'linear-gradient(135deg, #2b3a55, #4d6088)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="leaf" size={14} stroke="#f3dccb" sw={1.8} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'Newsreader, serif', fontSize: 15, color: '#1d2638', lineHeight: 1, fontWeight: 500 }}>Twogether</div>
          <div style={{ fontSize: 9, color: '#7a766c', letterSpacing: '0.1em', textTransform: 'uppercase', marginTop: 2 }}>May · viewing as</div>
        </div>
        <div style={{ display: 'flex', padding: 2, background: '#ece8de', borderRadius: 999 }}>
          {['B','C'].map(w => (
            <button key={w} onClick={() => setActiveUser(w)} style={{
              border: 'none', cursor: 'pointer', padding: 0, background: 'transparent',
              opacity: activeUser === w ? 1 : 0.45,
            }}>
              <Avatar who={w} size={22} ring={activeUser === w} />
            </button>
          ))}
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '4px 18px 90px', minHeight: 0 }}>
        {tab === 'home' && <MHome activeUser={activeUser} scenario={scenario} setTab={setTab} />}
        {tab === 'tx' && <MTx activeUser={activeUser} />}
        {tab === 'goals' && <MGoals scenario={scenario} />}
        {tab === 'life' && life && <MLife activeUser={activeUser} />}
        {tab === 'gram' && <PixelgramView activeUser={activeUser} dark={false} density={density} />}
        {tab === 'add' && <MAdd />}
      </div>

      {/* Tab bar */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        background: 'rgba(251,250,247,0.92)', backdropFilter: 'blur(20px)',
        borderTop: '1px solid #ece8de', padding: '8px 14px 28px',
        display: 'flex', justifyContent: 'space-around', alignItems: 'center',
      }}>
        {[
          { id: 'home',  icon: 'home',   label: 'Home' },
          { id: 'tx',    icon: 'list',   label: 'Activity' },
          { id: 'add',   icon: 'plus',   label: '', primary: true },
          { id: 'goals', icon: 'target', label: 'Goal' },
          { id: 'gram',  icon: 'sparkles', label: 'Grams' },
        ].map(it => (
          <button key={it.id} onClick={() => setTab(it.id)} style={{
            border: 'none', background: 'transparent', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
            color: tab === it.id ? '#2b3a55' : '#9c958a',
            padding: 0, fontFamily: 'Inter, system-ui',
          }}>
            {it.primary ? (
              <span style={{
                width: 42, height: 42, borderRadius: 21,
                background: '#1d2638', display: 'flex', alignItems: 'center', justifyContent: 'center',
                marginTop: -8, boxShadow: '0 4px 12px rgba(29,38,56,0.3)',
              }}>
                <Icon name="plus" size={20} stroke="#fbfaf7" sw={2} />
              </span>
            ) : (
              <Icon name={it.icon} size={21} stroke={tab === it.id ? '#2b3a55' : '#9c958a'} sw={1.7} />
            )}
            {it.label && <span style={{ fontSize: 9, fontWeight: 500, letterSpacing: '0.02em' }}>{it.label}</span>}
          </button>
        ))}
      </div>
    </div>
  );
};

const MHome = ({ activeUser, scenario, setTab }) => {
  const total = window.ACCOUNTS.filter(a => a.type !== 'credit' && (a.owner !== 'C' && a.owner !== 'B' || a.owner === activeUser || a.owner === 'J')).reduce((s,a)=>s+a.balance,0);
  const todaysTx = window.TRANSACTIONS.slice(0, 4);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Hero balance */}
      <div style={{ padding: '14px 4px 6px' }}>
        <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>Available together</div>
        <div style={{ fontFamily: 'Newsreader, serif', fontSize: 40, color: '#1d2638', letterSpacing: '-0.02em', fontWeight: 500, lineHeight: 1.05, marginTop: 4 }}>
          {window.fmt(total).replace('.00','')}
        </div>
        <div style={{ marginTop: 6, fontSize: 11.5, color: '#534e44', display: 'flex', gap: 10 }}>
          <span><span style={{ color: '#7a9b7e' }}>↑</span> +$2,240 May</span>
          <span style={{ color: '#7a766c' }}>·</span>
          <span style={{ color: '#7a766c' }}>5 cleared today</span>
        </div>
      </div>

      {/* Quick accounts */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
        {window.ACCOUNTS.slice(0, 4).map(a => (
          <div key={a.id} style={{
            background: '#fdfcf9', border: '1px solid #ece8de', borderRadius: 12, padding: 10,
          }}>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 }}>
              <BankBadge bank={a.bank} size={18} />
              <span style={{ fontSize: 10, color: '#7a766c', letterSpacing: '0.04em' }}>••{a.last4}</span>
            </div>
            <div style={{ fontSize: 11, color: '#534e44' }}>{a.name}</div>
            <div style={{ fontFamily: 'Newsreader, serif', fontSize: 16, color: a.balance < 0 ? '#c97a4a' : '#1d2638', marginTop: 2, fontWeight: 500 }}>
              {window.fmt(a.balance).replace('.00','')}
            </div>
          </div>
        ))}
      </div>

      {/* Goal hero */}
      {scenario && (
        <div onClick={() => setTab('goals')} style={{
          padding: 16, borderRadius: 14,
          background: 'linear-gradient(135deg, #fbfaf7, #f3dccb)',
          border: '1px solid #e8d8c2', cursor: 'pointer',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
            <Icon name="target" size={12} stroke="#c97a4a" sw={2} />
            <span style={{ fontSize: 9.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#c97a4a', fontWeight: 600 }}>Active goal</span>
          </div>
          <div style={{ fontFamily: 'Newsreader, serif', fontSize: 17, color: '#1d2638', lineHeight: 1.3, fontWeight: 500 }}>
            Cindy quits cleaning + starts ceramics class
          </div>
          <div style={{ display: 'flex', gap: 12, marginTop: 12, fontSize: 11 }}>
            <span><span style={{ color: '#7a766c' }}>Net</span> <b style={{ color: '#c97a4a' }}>−$975</b></span>
            <span><span style={{ color: '#7a766c' }}>Cuts</span> <b style={{ color: '#7a9b7e' }}>+$612</b></span>
            <span><span style={{ color: '#7a766c' }}>Gap</span> <b style={{ color: '#1d2638' }}>$363</b></span>
          </div>
          <div style={{ marginTop: 10 }}>
            <Bar pct={63} color="#c97a4a" />
            <div style={{ fontSize: 10, color: '#7a766c', marginTop: 4 }}>Tap to open the plan →</div>
          </div>
        </div>
      )}

      {/* Inbox */}
      <div style={{ padding: 14, borderRadius: 12, background: '#fdfcf9', border: '1px solid #ece8de' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
          <Icon name="bell" size={14} stroke="#c97a4a" />
          <span style={{ fontSize: 11.5, color: '#1d2638', fontWeight: 500, flex: 1 }}>2 transactions need a quick look</span>
          <span style={{ fontSize: 10, color: '#7a766c' }}>From {activeUser === 'B' ? 'Cindy' : 'Branden'}</span>
        </div>
        {window.TRANSACTIONS.filter(t => !t.approved).slice(0, 2).map((t, i) => (
          <div key={t.id} style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '8px 0', borderTop: i ? '1px solid #ece8de' : 'none',
          }}>
            <Avatar who={t.who} size={22} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, color: '#1d2638', fontWeight: 500 }}>{t.merchant}</div>
              <div style={{ fontSize: 10, color: '#7a766c' }}>{t.flag === 'needs-split' ? 'Split?' : 'Confirm category'}</div>
            </div>
            <span style={{ fontSize: 12, color: '#1d2638', fontVariantNumeric: 'tabular-nums' }}>{window.fmt(t.amt).replace('.00','')}</span>
          </div>
        ))}
      </div>

      {/* Today */}
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '4px 4px 8px' }}>
          <span style={{ fontFamily: 'Newsreader, serif', fontSize: 17, color: '#1d2638', fontWeight: 500 }}>Today</span>
          <button onClick={() => setTab('tx')} style={{ border: 'none', background: 'transparent', color: '#7a766c', fontSize: 11, cursor: 'pointer' }}>See all →</button>
        </div>
        <div style={{ background: '#fdfcf9', border: '1px solid #ece8de', borderRadius: 12, padding: '0 12px' }}>
          {todaysTx.map((t, i) => <MTxRow key={t.id} t={t} first={i === 0} />)}
        </div>
      </div>
    </div>
  );
};

const MTxRow = ({ t, first }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderTop: first ? 'none' : '1px solid #ece8de' }}>
    <BankBadge bank={t.bank} size={22} />
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 12.5, color: '#1d2638', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 4 }}>
        {t.merchant}
        {t.private && <Icon name="lock" size={9} stroke="#7a766c" />}
      </div>
      <div style={{ fontSize: 10, color: '#7a766c', marginTop: 1 }}>{t.cat}</div>
    </div>
    <Avatar who={t.who} size={16} />
    <span style={{ fontSize: 12, fontVariantNumeric: 'tabular-nums', color: t.amt > 0 ? '#7a9b7e' : '#1d2638' }}>
      {(t.amt > 0 ? '+' : '') + window.fmt(t.amt).replace('.00','')}
    </span>
  </div>
);

const MTx = ({ activeUser }) => {
  const grouped = {};
  window.TRANSACTIONS.forEach(t => { (grouped[t.date] ||= []).push(t); });
  return (
    <div>
      <div style={{ padding: '12px 4px 14px' }}>
        <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>Activity · May</div>
        <div style={{ fontFamily: 'Newsreader, serif', fontSize: 24, color: '#1d2638', fontWeight: 500, marginTop: 2 }}>All transactions</div>
      </div>
      {Object.entries(grouped).slice(0, 5).map(([date, txs]) => (
        <div key={date} style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase', color: '#7a766c', padding: '4px 4px 6px' }}>
            {new Date(date + 'T12:00').toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })}
          </div>
          <div style={{ background: '#fdfcf9', border: '1px solid #ece8de', borderRadius: 12, padding: '0 12px' }}>
            {txs.map((t, i) => <MTxRow key={t.id} t={t} first={i === 0} />)}
          </div>
        </div>
      ))}
    </div>
  );
};

const MGoals = ({ scenario }) => {
  const [classCost, setClassCost] = useM(275);
  const [trims, setTrims] = useM(290);
  const gap = 700 + classCost - trims;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ padding: '12px 4px 4px' }}>
        <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#c97a4a', fontWeight: 600 }}>Active goal</div>
        <div style={{ fontFamily: 'Newsreader, serif', fontSize: 22, color: '#1d2638', fontWeight: 500, marginTop: 2, lineHeight: 1.2 }}>
          The class & quitting plan
        </div>
      </div>

      <div style={{ padding: 14, background: '#faf7f0', borderRadius: 12, border: '1px solid #ece8de' }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <Avatar who="C" size={28} />
          <div>
            <div style={{ fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#7a766c' }}>Cindy stated</div>
            <p style={{ margin: '4px 0 0', fontFamily: 'Newsreader, serif', fontStyle: 'italic', fontSize: 13.5, color: '#1d2638', lineHeight: 1.45 }}>
              "Quit cleaning, take the ceramics class. Don't touch savings."
            </p>
          </div>
        </div>
      </div>

      {/* Result hero */}
      <div style={{
        padding: 16, borderRadius: 14,
        background: gap > 0 ? 'linear-gradient(180deg, #fbfaf7, #fff3ec)' : 'linear-gradient(180deg, #fbfaf7, #eff5ec)',
        border: '1px solid #ece8de',
      }}>
        <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>Per month</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 2 }}>
          <span style={{ fontFamily: 'Newsreader, serif', fontSize: 38, fontWeight: 500, color: gap > 0 ? '#c97a4a' : '#7a9b7e', letterSpacing: '-0.02em', lineHeight: 1 }}>
            {gap > 0 ? '−' : '+'}{window.fmtShort(Math.abs(gap))}
          </span>
        </div>
        <p style={{ margin: '8px 0 0', fontSize: 12, color: '#534e44', lineHeight: 1.45 }}>
          {gap > 0
            ? <>Short by <b>{window.fmtShort(gap)}</b>. Trim more or keep ~{Math.ceil(gap / 25) * 5}h of cleaning.</>
            : <>Plan covers it.</>
          }
        </p>
      </div>

      {/* Sliders */}
      <div style={{ background: '#fdfcf9', border: '1px solid #ece8de', borderRadius: 12, padding: 14 }}>
        <MSlider label="Class cost / month" value={classCost} onChange={setClassCost} min={0} max={500} step={25} />
        <div style={{ height: 1, background: '#ece8de', margin: '14px 0' }} />
        <MSlider label="Monthly trims locked in" value={trims} onChange={setTrims} min={0} max={800} step={20} sub="From subs, groceries, coffee, personal" />
      </div>

      {/* Plan steps */}
      <div style={{ background: '#fdfcf9', border: '1px solid #ece8de', borderRadius: 12, padding: 14 }}>
        <div style={{ fontFamily: 'Newsreader, serif', fontSize: 15, color: '#1d2638', fontWeight: 500, marginBottom: 10 }}>4-week ramp</div>
        {[
          ['W1', 'Cancel 3 subs', '−$48'],
          ['W2', 'Cut grocery target', '−$120'],
          ['W3', 'Last day cleaning', '$0'],
          ['W4', 'Class starts', '+$275'],
        ].map(([w, lbl, amt], i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderTop: i ? '1px solid #ece8de' : 'none' }}>
            <span style={{
              width: 26, height: 26, borderRadius: 13,
              background: i < 2 ? '#dde3d3' : '#ece8de', color: i < 2 ? '#3e4d34' : '#7a766c',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 9.5, fontWeight: 600, letterSpacing: '0.04em',
            }}>{w}</span>
            <span style={{ flex: 1, fontSize: 12.5, color: '#1d2638' }}>{lbl}</span>
            <span style={{ fontSize: 12, color: '#534e44', fontVariantNumeric: 'tabular-nums' }}>{amt}</span>
            {i < 2 && <Icon name="check" size={14} stroke="#7a9b7e" sw={2} />}
          </div>
        ))}
      </div>

      <button style={{
        padding: '14px', borderRadius: 12, border: 'none',
        background: '#1d2638', color: '#fbfaf7', fontSize: 13, fontWeight: 500,
        fontFamily: 'Inter, system-ui', cursor: 'pointer',
      }}>Lock this plan in</button>
    </div>
  );
};

const MSlider = ({ label, value, onChange, min, max, step, sub }) => (
  <div>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
      <div>
        <div style={{ fontSize: 12, color: '#1d2638', fontWeight: 500 }}>{label}</div>
        {sub && <div style={{ fontSize: 10, color: '#7a766c' }}>{sub}</div>}
      </div>
      <span style={{ fontFamily: 'Newsreader, serif', fontSize: 20, color: '#1d2638', fontWeight: 500 }}>${value}</span>
    </div>
    <input type="range" min={min} max={max} step={step} value={value}
      onChange={e => onChange(Number(e.target.value))}
      style={{ width: '100%', accentColor: '#2b3a55' }} />
  </div>
);

const MLife = () => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
    <div style={{ padding: '12px 4px 0' }}>
      <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>Life · today</div>
      <div style={{ fontFamily: 'Newsreader, serif', fontSize: 22, color: '#1d2638', fontWeight: 500 }}>How are you?</div>
    </div>
    <div style={{ background: '#fdfcf9', border: '1px solid #ece8de', borderRadius: 12, padding: 14 }}>
      <div style={{ fontSize: 11, color: '#534e44', marginBottom: 10 }}>Quick mood check-in</div>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 6 }}>
        {[1,2,3,4,5].map(n => (
          <button key={n} style={{
            flex: 1, padding: '14px 0', borderRadius: 10,
            border: '1px solid #ece8de', background: n === 4 ? '#dde3d3' : '#fbfaf7',
            color: '#1d2638', fontFamily: 'Newsreader, serif', fontSize: 18, fontWeight: 500, cursor: 'pointer',
          }}>{n}</button>
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9, color: '#7a766c', padding: '4px 6px 0' }}>
        <span>Rough</span><span>Good</span>
      </div>
    </div>
    <div style={{ background: '#fdfcf9', border: '1px solid #ece8de', borderRadius: 12, padding: 14 }}>
      <div style={{ fontFamily: 'Newsreader, serif', fontSize: 15, color: '#1d2638', fontWeight: 500, marginBottom: 10 }}>Habits — this week</div>
      {window.HABITS.map((h, i) => (
        <div key={h.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderTop: i ? '1px solid #ece8de' : 'none' }}>
          {h.shared ? <AvatarPair size={18} /> : <Avatar who={h.who} size={20} />}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12, color: '#1d2638', fontWeight: 500 }}>{h.name}</div>
            <div style={{ fontSize: 10, color: '#7a766c' }}>{h.streak}-day streak</div>
          </div>
          <div style={{ display: 'flex', gap: 3 }}>
            {h.weekly.map((d, j) => (
              <span key={j} style={{
                width: 13, height: 13, borderRadius: 4,
                background: d ? (h.shared ? '#5a6b4f' : window.PEOPLE[h.who].color) : '#ece8de',
              }} />
            ))}
          </div>
        </div>
      ))}
    </div>
    <div style={{ padding: 14, background: 'linear-gradient(135deg, #fbfaf7, #dde3d3)', borderRadius: 12, border: '1px solid #bdc8b0' }}>
      <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#3e4d34', fontWeight: 600 }}>Pattern</div>
      <p style={{ margin: '4px 0 0', fontSize: 12.5, color: '#1d2638', lineHeight: 1.45 }}>
        Your mood ticks up <b>+0.7</b> on days the class is mentioned.
      </p>
    </div>
  </div>
);

const MAdd = () => (
  <div>
    <div style={{ padding: '12px 4px' }}>
      <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a766c' }}>Quick add</div>
      <div style={{ fontFamily: 'Newsreader, serif', fontSize: 22, color: '#1d2638', fontWeight: 500 }}>What happened?</div>
    </div>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
      {[
        ['plus','Add expense','#1d2638'],
        ['arrow-up','Add income','#7a9b7e'],
        ['split','Split a bill','#b89968'],
        ['target','State a goal','#c97a4a'],
        ['heart','Mood check-in','#5a6b4f'],
        ['chat','Note for partner','#4d6088'],
      ].map(([ic, lbl, c], i) => (
        <button key={i} style={{
          padding: '20px 14px', borderRadius: 14, border: '1px solid #ece8de',
          background: '#fdfcf9', cursor: 'pointer',
          display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 8,
          fontFamily: 'Inter, system-ui',
        }}>
          <span style={{ width: 32, height: 32, borderRadius: 8, background: c + '22', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name={ic} size={17} stroke={c} sw={1.8} />
          </span>
          <span style={{ fontSize: 12.5, color: '#1d2638', fontWeight: 500 }}>{lbl}</span>
        </button>
      ))}
    </div>
  </div>
);

window.MobilePhone = MobilePhone;
