// Household — real collaborative households backed by Supabase auth + RLS.

const PageHousehold = () => {
  const { state, derived, household, createHousehold, leaveHousehold } = useAppState();
  const { user } = useAuth();
  const [creating, setCreating] = React.useState(false);
  const [leaving, setLeaving] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const [error, setError] = React.useState('');

  const inviteLink = household?.inviteToken
    ? `${window.location.origin}${window.location.pathname}?invite=${household.inviteToken}`
    : null;

  const handleCreate = async () => {
    setCreating(true);
    setError('');
    try { await createHousehold(); } catch (e) { setError(e.message); } finally { setCreating(false); }
  };

  const handleLeave = async () => {
    if (!confirm('Leave this household? Your data stays yours, but you will no longer see each other\'s information.')) return;
    setLeaving(true);
    try { await leaveHousehold(); } catch (e) { setError(e.message); } finally { setLeaving(false); }
  };

  const handleCopy = () => {
    navigator.clipboard.writeText(inviteLink).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2500);
    });
  };

  // Per-user breakdown (group by user_id, not member)
  const myUserId   = user?.id;
  const partnerUserId = household?.partner?.id;

  const userSummary = (uid, label, email) => {
    const txs     = state.transactions.filter(t => t.userId === uid || (!t.userId && uid === myUserId));
    const income  = txs.filter(t => t.type === 'income').reduce((a, t) => a + t.amount, 0);
    const expense = txs.filter(t => t.type === 'expense').reduce((a, t) => a + t.amount, 0);
    const debts   = state.debts.filter(d => d.userId === uid || (!d.userId && uid === myUserId)).reduce((a, d) => a + d.balance, 0);
    const goals   = state.goals.filter(g => g.userId === uid || (!g.userId && uid === myUserId)).reduce((a, g) => a + g.saved, 0);
    const firstName = email
      ? email.split('@')[0].split(/[._+\-]/)[0].replace(/\d+$/, '')
      : label;
    const name = firstName.charAt(0).toUpperCase() + firstName.slice(1).toLowerCase();
    return { uid, name, email, income, expense, net: income - expense, debts, goals, txCount: txs.length };
  };

  // ── No household yet ──────────────────────────────────────────────────────────
  if (!household) return (
    <div>
      <div className="topbar">
        <div>
          <h1 className="page-title"><span className="serif">Household</span></h1>
          <div className="page-sub">Invite a partner or family member to share your budget</div>
        </div>
      </div>

      {error && <div style={{ background:'#fff1f0', border:'1px solid #fca5a5', borderRadius:10, padding:'12px 14px', fontSize:13, color:'#b91c1c', marginBottom:16 }}>{error}</div>}

      {/* Your profile */}
      <div className="card card-pad-lg fade-up" style={{ marginBottom:20 }}>
        <div className="card-title">Your profile</div>
        <div className="row" style={{ gap:14 }}>
          <div style={{ width:44, height:44, borderRadius:'50%', background:'var(--ink)', color:'white', display:'flex', alignItems:'center', justifyContent:'center', fontSize:16, fontWeight:600, flexShrink:0 }}>
            {(user?.email?.[0] || '?').toUpperCase()}
          </div>
          <div>
            <div style={{ fontWeight:500, fontSize:15 }}>{user?.email}</div>
            <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:2 }}>Solo mode · {state.transactions.length} transactions</div>
          </div>
        </div>
      </div>

      {/* Invite section */}
      <div className="card card-pad-lg fade-up" style={{ textAlign:'center', animationDelay:'0.1s' }}>
        <div style={{ width:52, height:52, borderRadius:16, background:'var(--surface-2)', border:'1px solid var(--line)', display:'inline-flex', alignItems:'center', justifyContent:'center', marginBottom:16 }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--ink-2)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
            <circle cx="9" cy="7" r="4"/>
            <line x1="19" y1="8" x2="19" y2="14"/>
            <line x1="22" y1="11" x2="16" y2="11"/>
          </svg>
        </div>
        <h3 style={{ fontSize:18, fontWeight:500, margin:'0 0 8px', color:'var(--ink)' }}>Invite a collaborator</h3>
        <p style={{ fontSize:13.5, color:'var(--ink-3)', maxWidth:360, margin:'0 auto 24px' }}>
          Generate a one-time invite link and share it with your partner or family member. Once they join, you'll see each other's data combined.
        </p>
        <button
          className="btn btn-primary"
          onClick={handleCreate}
          disabled={creating}
          style={{ margin:'0 auto' }}
        >
          {creating ? 'Generating…' : '🔗 Generate invite link'}
        </button>
      </div>
    </div>
  );

  // ── Pending invite ────────────────────────────────────────────────────────────
  if (household.status === 'pending') return (
    <div>
      <div className="topbar">
        <div>
          <h1 className="page-title"><span className="serif">Household</span></h1>
          <div className="page-sub">Waiting for your collaborator to join</div>
        </div>
      </div>

      {error && <div style={{ background:'#fff1f0', border:'1px solid #fca5a5', borderRadius:10, padding:'12px 14px', fontSize:13, color:'#b91c1c', marginBottom:16 }}>{error}</div>}

      <div className="card card-pad-lg fade-up" style={{ textAlign:'center' }}>
        <div style={{ width:52, height:52, borderRadius:16, background:'#fef9c3', border:'1px solid #fde047', display:'inline-flex', alignItems:'center', justifyContent:'center', marginBottom:16, fontSize:22 }}>
          ⏳
        </div>
        <h3 style={{ fontSize:18, fontWeight:500, margin:'0 0 8px', color:'var(--ink)' }}>Invite pending</h3>
        <p style={{ fontSize:13.5, color:'var(--ink-3)', maxWidth:380, margin:'0 auto 20px' }}>
          Share this link with your collaborator. Once they sign in and open it, you'll both be connected.
        </p>

        {/* Invite link box */}
        <div style={{ display:'flex', gap:8, maxWidth:480, margin:'0 auto 24px', alignItems:'stretch' }}>
          <div style={{ flex:1, padding:'10px 12px', background:'var(--surface-2)', border:'1px solid var(--line)', borderRadius:8, fontSize:12, color:'var(--ink-3)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', fontFamily:'monospace' }}>
            {inviteLink}
          </div>
          <button
            className="btn btn-primary"
            onClick={handleCopy}
            style={{ flexShrink:0 }}
          >
            {copied ? '✓ Copied!' : 'Copy link'}
          </button>
        </div>

        <button
          className="btn btn-ghost btn-sm"
          onClick={handleLeave}
          disabled={leaving}
          style={{ color:'var(--coral)' }}
        >
          Cancel invite
        </button>
      </div>
    </div>
  );

  // ── Active household ──────────────────────────────────────────────────────────
  const me      = userSummary(myUserId,      'You',     user?.email);
  const partner = userSummary(partnerUserId, 'Partner', household.partner?.email);
  const totalIncome = me.income + partner.income;

  return (
    <div>
      <div className="topbar">
        <div>
          <h1 className="page-title"><span className="serif">Household</span></h1>
          <div className="page-sub">2 people · combined view</div>
        </div>
        <button
          className="btn btn-ghost btn-sm"
          onClick={handleLeave}
          disabled={leaving}
          style={{ color:'var(--coral)' }}
        >
          {leaving ? 'Leaving…' : 'Leave household'}
        </button>
      </div>

      {error && <div style={{ background:'#fff1f0', border:'1px solid #fca5a5', borderRadius:10, padding:'12px 14px', fontSize:13, color:'#b91c1c', marginBottom:16 }}>{error}</div>}

      {/* Income split bar */}
      <div className="card card-pad-lg fade-up" style={{ marginBottom:20 }}>
        <div className="card-title">Who brings in what</div>
        <div style={{ display:'flex', height:56, borderRadius:12, overflow:'hidden', marginBottom:14 }}>
          {[me, partner].map((p, i) => {
            const pct = totalIncome ? p.income / totalIncome : 0.5;
            const bg = i === 0 ? 'var(--ink)' : 'var(--mint-deep)';
            return (
              <div key={i} style={{ width:`${pct*100}%`, background: bg, color:'white', display:'flex', alignItems:'center', padding:'0 14px', fontSize:13, fontWeight:500, animation:`fadeIn 0.6s ${i*0.1}s both` }}>
                <div style={{ width:28, height:28, borderRadius:'50%', background:'rgba(255,255,255,0.2)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:12, fontWeight:600, marginRight:8, flexShrink:0 }}>
                  {p.name[0]}
                </div>
                <div>
                  <div>{p.name}</div>
                  <div className="mono" style={{ fontSize:10.5, opacity:0.85, fontWeight:400 }}>{fmtZARShort(p.income)} · {(pct*100).toFixed(0)}%</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Per-person cards */}
      <div className="grid stagger" style={{ gridTemplateColumns:'repeat(2, 1fr)', gap:18 }}>
        {[me, partner].map((p, i) => (
          <div key={i} className="card card-pad-lg fade-up">
            <div className="row" style={{ gap:12, marginBottom:18 }}>
              <div style={{ width:40, height:40, borderRadius:'50%', background: i === 0 ? 'var(--ink)' : 'var(--mint-deep)', color:'white', display:'flex', alignItems:'center', justifyContent:'center', fontSize:15, fontWeight:600, flexShrink:0 }}>
                {p.name[0]}
              </div>
              <div>
                <div className="serif" style={{ fontSize:20 }}>{p.name}</div>
                <div style={{ fontSize:11, color:'var(--ink-3)', marginTop:1 }}>{p.email || ''}</div>
              </div>
            </div>

            <div className="grid" style={{ gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:14 }}>
              <div style={{ padding:'10px 12px', background:'var(--mint-soft)', borderRadius:10 }}>
                <div style={{ fontSize:10, color:'var(--mint-deep)', textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:500 }}>Income</div>
                <div className="mono" style={{ fontWeight:500, fontSize:15, marginTop:2 }}>{fmtZARShort(p.income)}</div>
              </div>
              <div style={{ padding:'10px 12px', background:'var(--coral-soft)', borderRadius:10 }}>
                <div style={{ fontSize:10, color:'oklch(0.55 0.15 30)', textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:500 }}>Spent</div>
                <div className="mono" style={{ fontWeight:500, fontSize:15, marginTop:2 }}>{fmtZARShort(p.expense)}</div>
              </div>
            </div>

            <div className="row-between" style={{ padding:'10px 0', borderTop:'1px solid var(--line-2)', fontSize:13 }}>
              <span style={{ color:'var(--ink-3)' }}>Net</span>
              <span className="mono" style={{ fontWeight:500, color: p.net >= 0 ? 'var(--mint-deep)' : 'var(--coral)' }}>
                {p.net >= 0 ? '+' : ''}{fmtZAR(p.net, { cents:false })}
              </span>
            </div>
            <div className="row-between" style={{ padding:'10px 0', borderTop:'1px solid var(--line-2)', fontSize:13 }}>
              <span style={{ color:'var(--ink-3)' }}>Debt held</span>
              <span className="mono">{fmtZARShort(p.debts)}</span>
            </div>
            <div className="row-between" style={{ padding:'10px 0', borderTop:'1px solid var(--line-2)', fontSize:13 }}>
              <span style={{ color:'var(--ink-3)' }}>Saved towards goals</span>
              <span className="mono">{fmtZARShort(p.goals)}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

Object.assign(window, { PageHousehold });
