// Minha conta — Perfil, Plano & Créditos, Histórico, Segurança.

function Account({ navigate }) {
  const [tab, setTab] = useState('profile'); // profile | plan | history | security
  const user = window.USER;
  if (!user) return null;

  return (
    <div style={{ minHeight:'100dvh', background:'var(--bg)' }}>
      <AccountNav navigate={navigate}/>
      <div className="m-section" style={{ maxWidth: 960, margin:'0 auto', padding:'40px 32px 64px' }}>
        <div style={{ marginBottom: 24 }}>
          <button onClick={() => navigate('#/dashboard')} className="tap-fade"
            style={{ fontSize: 13, color:'var(--ink-3)', display:'flex', alignItems:'center', gap: 6, marginBottom: 14 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M15 6l-6 6 6 6"/></svg>
            Voltar ao editor
          </button>
          <h1 className="serif m-h1" style={{ fontSize: 48, lineHeight: 1, margin: 0, letterSpacing:'-0.015em' }}>
            Minha conta
          </h1>
        </div>

        <div className="m-single-col" style={{ display:'grid', gridTemplateColumns:'220px 1fr', gap: 32, alignItems:'flex-start' }}>
          <aside className="m-account-tabs" style={{ position:'sticky', top: 20 }}>
            <TabButton active={tab==='profile'}  onClick={() => setTab('profile')}>Perfil</TabButton>
            <TabButton active={tab==='plan'}     onClick={() => setTab('plan')}>Plano & créditos</TabButton>
            <TabButton active={tab==='history'}  onClick={() => setTab('history')}>Histórico</TabButton>
            <TabButton active={tab==='security'} onClick={() => setTab('security')}>Segurança</TabButton>
            <div className="hide-mobile" style={{ marginTop: 14, borderTop:'1px solid var(--line)', paddingTop: 14 }}>
              <button onClick={async () => { await window.DB.logout(); navigate('#/landing'); }}
                style={{
                  width:'100%', textAlign:'left', padding:'10px 14px', borderRadius: 10,
                  fontSize: 13, color:'var(--ink-3)',
                }}>
                Sair da conta
              </button>
            </div>
          </aside>

          <section>
            {tab === 'profile'  && <ProfileTab user={user}/>}
            {tab === 'plan'     && <PlanTab user={user} navigate={navigate}/>}
            {tab === 'history'  && <HistoryTab/>}
            {tab === 'security' && <SecurityTab user={user}/>}
          </section>
        </div>
      </div>
    </div>
  );
}

function TabButton({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      display:'block', width:'100%', textAlign:'left',
      padding:'11px 14px', borderRadius: 10, fontSize: 14, fontWeight: active ? 600 : 400,
      background: active ? 'var(--paper)' : 'transparent',
      border: '1px solid ' + (active ? 'var(--line)' : 'transparent'),
      color: active ? 'var(--ink)' : 'var(--ink-2)',
      marginBottom: 4,
    }}>{children}</button>
  );
}

function AccountNav({ navigate }) {
  return (
    <nav className="m-nav" style={{
      display:'flex', alignItems:'center', justifyContent:'space-between',
      padding:'20px 32px', borderBottom:'1px solid var(--line)', background:'var(--paper)',
      paddingTop: 'calc(14px + var(--safe-top))',
      position:'sticky', top: 0, zIndex: 40,
    }}>
      <button onClick={() => navigate('#/landing')} style={{ display:'flex', alignItems:'center', gap: 10 }}>
        <AftershotMark/>
        <span className="serif" style={{ fontSize: 22 }}>Aftershot</span>
      </button>
      <button onClick={() => navigate('#/dashboard')} className="tap-fade"
        style={{ fontSize: 13, color:'var(--ink-2)', padding:'10px 14px', borderRadius: 10, border:'1px solid var(--line)', background:'var(--paper)' }}>
        Ir para o editor
      </button>
    </nav>
  );
}

// ── Perfil ────────────────────────────────────────────────────────────────
function ProfileTab({ user }) {
  const [name, setName] = useState(user.name || '');
  const [listings, setListings] = useState(user.listings || 1);
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState(null);

  const save = async () => {
    setSaving(true); setMsg(null);
    try {
      await window.DB.updateUser({ name, listings: Number(listings) });
      setMsg({ tone:'ok', text:'Alterações salvas.' });
    } catch (e) {
      setMsg({ tone:'err', text: e.message });
    } finally {
      setSaving(false);
    }
  };

  const initial = (user.name || user.email || '?').trim().charAt(0).toUpperCase();

  return (
    <Card title="Perfil" desc="Dados básicos da sua conta.">
      <div style={{ display:'flex', gap: 18, alignItems:'center', marginBottom: 24 }}>
        {user.avatarUrl ? (
          <img src={user.avatarUrl} alt="" style={{ width: 72, height: 72, borderRadius:'50%', objectFit:'cover' }}/>
        ) : (
          <div style={{
            width: 72, height: 72, borderRadius:'50%',
            background:'var(--accent)', color:'#fff',
            display:'flex', alignItems:'center', justifyContent:'center',
            fontFamily:'var(--serif)', fontSize: 32,
          }}>{initial}</div>
        )}
        <div>
          <div className="serif" style={{ fontSize: 22 }}>{user.name || '—'}</div>
          <div style={{ fontSize: 13, color:'var(--ink-3)' }}>{user.email}</div>
        </div>
      </div>

      <Row label="Nome">
        <input value={name} onChange={e => setName(e.target.value)} style={input}/>
      </Row>
      <Row label="E-mail">
        <input value={user.email} readOnly style={{...input, background:'var(--bg-deep)', color:'var(--ink-3)'}}/>
      </Row>
      <Row label="Quantos imóveis você aluga?">
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap: 8, maxWidth: 340, width:'100%' }}>
          {[1,2,3,4].map(n => (
            <button key={n} type="button" onClick={() => setListings(n)}
              style={{
                padding:'12px 0', borderRadius: 10, fontSize: 14, fontWeight: 500,
                border:'1px solid ' + (Number(listings)===n ? 'var(--ink)' : 'var(--line)'),
                background: Number(listings)===n ? 'var(--bg-deep)' : 'var(--paper)',
              }}>{n === 4 ? '4+' : n}</button>
          ))}
        </div>
      </Row>

      {msg && <Msg {...msg}/>}

      <Button variant="primary" size="lg" onClick={save} disabled={saving}>
        {saving ? 'Salvando…' : 'Salvar alterações'}
      </Button>
    </Card>
  );
}

// ── Plano & Créditos ──────────────────────────────────────────────────────
function PlanTab({ user, navigate }) {
  const available = Math.max(0, (user.creditsTotal || 0) - (user.creditsUsed || 0));
  const pct = user.creditsTotal ? Math.round((user.creditsUsed / user.creditsTotal) * 100) : 0;

  return (
    <Card title="Plano & créditos" desc="Seu plano atual e uso de créditos.">
      <div style={{
        padding: 20, border:'1px solid var(--line)', borderRadius: 14, marginBottom: 20, background:'var(--bg-warm)',
      }}>
        <div style={{ fontSize: 11, color:'var(--ink-3)', letterSpacing:'.08em', textTransform:'uppercase' }}>Plano atual</div>
        <div className="serif" style={{ fontSize: 34, lineHeight: 1.1, marginTop: 4 }}>{user.planName || 'Gratuito'}</div>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap: 8, marginBottom: 20 }}>
        <Stat k="Disponíveis" v={available} accent/>
        <Stat k="Usados" v={user.creditsUsed || 0}/>
        <Stat k="Total" v={user.creditsTotal || 0}/>
      </div>

      <div style={{ marginBottom: 20 }}>
        <div style={{ display:'flex', justifyContent:'space-between', fontSize: 12, color:'var(--ink-3)', marginBottom: 6 }}>
          <span>Progresso de uso</span><span>{pct}%</span>
        </div>
        <div style={{ height: 6, background:'var(--line)', borderRadius: 999, overflow:'hidden' }}>
          <div style={{ width: `${pct}%`, height:'100%', background:'var(--accent)' }}/>
        </div>
      </div>

      <div className="m-stack" style={{ display:'flex', gap: 10, flexWrap:'wrap' }}>
        <Button variant="primary" size="lg" onClick={() => navigate('#/checkout?plan=profissional')} className="m-btn-full">
          Comprar mais créditos
        </Button>
        <Button variant="secondary" size="lg" onClick={() => navigate('#/dashboard')} className="m-btn-full">
          Ir para o editor
        </Button>
      </div>
      <div className="show-mobile" style={{ display:'none', marginTop: 18, borderTop:'1px solid var(--line)', paddingTop: 14 }}>
        <Button variant="ghost" size="md" onClick={async () => { await window.DB.logout(); navigate('#/landing'); }} style={{ width:'100%', color:'var(--ink-3)' }}>
          Sair da conta
        </Button>
      </div>
    </Card>
  );
}

function Stat({ k, v, accent }) {
  return (
    <div style={{
      padding: 14, background:'var(--paper)', border:'1px solid var(--line)', borderRadius: 12,
    }}>
      <div style={{ fontSize: 11, color:'var(--ink-3)', letterSpacing:'.06em', textTransform:'uppercase' }}>{k}</div>
      <div className="serif" style={{
        fontSize: 28, marginTop: 4, color: accent ? 'var(--accent)' : 'var(--ink)',
      }}>{v}</div>
    </div>
  );
}

// ── Histórico ─────────────────────────────────────────────────────────────
function HistoryTab() {
  const [items, setItems] = useState(null);
  const [err, setErr] = useState(null);

  useEffect(() => {
    window.DB.listPurchases().then(setItems).catch(e => setErr(e.message));
  }, []);

  if (err) return <Card title="Histórico"><Msg tone="err" text={err}/></Card>;
  if (items === null) return <Card title="Histórico"><div style={{ color:'var(--ink-3)', fontSize: 14 }}>Carregando…</div></Card>;
  if (items.length === 0) {
    return (
      <Card title="Histórico" desc="Suas compras aparecem aqui.">
        <div style={{ padding: 28, textAlign:'center', color:'var(--ink-3)', fontSize: 14 }}>
          Você ainda não fez nenhuma compra.
        </div>
      </Card>
    );
  }

  const fmtDate = (ts) => ts ? new Date(ts).toLocaleString('pt-BR', { day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit' }) : '—';
  const fmtMoney = (n) => `R$ ${Number(n).toFixed(2).replace('.', ',')}`;

  return (
    <Card title="Histórico" desc="Todas as suas compras.">
      <div style={{ border:'1px solid var(--line)', borderRadius: 12, overflow:'hidden' }}>
        {items.map((p, i) => (
          <div key={p.orderId || i} style={{
            display:'grid', gridTemplateColumns:'1fr auto', gap: 12, alignItems:'center',
            padding:'16px 18px', borderTop: i === 0 ? 'none' : '1px solid var(--line)',
            background: p.status === 'paid' ? 'var(--paper)' : 'var(--bg-warm)',
          }}>
            <div>
              <div style={{ display:'flex', gap: 8, alignItems:'center', marginBottom: 4 }}>
                <span style={{ fontWeight: 600, fontSize: 15 }}>{p.planName || '—'}</span>
                <StatusBadge status={p.status}/>
              </div>
              <div style={{ fontSize: 12, color:'var(--ink-3)' }}>
                {p.credits} créditos · {p.method === 'pix' ? 'PIX' : 'Cartão'} · {fmtDate(p.paidAt || p.createdAt)}
              </div>
              {p.receiptCode && (
                <div style={{ fontSize: 11, color:'var(--ink-4)', marginTop: 4, fontFamily:'var(--mono)' }}>
                  Código: {p.receiptCode}
                </div>
              )}
            </div>
            <div style={{ textAlign:'right' }}>
              <div className="serif" style={{ fontSize: 22 }}>{fmtMoney(p.amount)}</div>
              {p.receiptCode && p.status === 'paid' && (
                <a href={`/api/checkout/receipt/${p.receiptCode}.html`} target="_blank" rel="noopener"
                  style={{ fontSize: 12, color:'var(--accent)', textDecoration:'underline' }}>
                  Ver recibo
                </a>
              )}
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

function StatusBadge({ status }) {
  const map = {
    paid:     { bg:'#EAF2E4', fg:'#5C6B3F', label:'Pago' },
    pending:  { bg:'#F3E3D8', fg:'#A64E30', label:'Pendente' },
    failed:   { bg:'#FDECE7', fg:'#7A2E18', label:'Falhou' },
    canceled: { bg:'#EFE8DD', fg:'#6B6157', label:'Cancelado' },
  };
  const s = map[status] || { bg:'var(--bg-deep)', fg:'var(--ink-3)', label: status || '—' };
  return (
    <span style={{
      fontSize: 10, fontWeight: 600, letterSpacing:'.04em', textTransform:'uppercase',
      padding:'3px 8px', borderRadius: 999, background: s.bg, color: s.fg,
    }}>{s.label}</span>
  );
}

// ── Segurança ─────────────────────────────────────────────────────────────
function SecurityTab({ user }) {
  const [curr, setCurr] = useState('');
  const [next, setNext] = useState('');
  const [conf, setConf] = useState('');
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState(null);

  const needsCurrent = !!user.hasPassword;

  const submit = async (e) => {
    e?.preventDefault?.();
    setMsg(null);
    if (next.length < 6) return setMsg({ tone:'err', text:'Nova senha precisa ter no mínimo 6 caracteres.' });
    if (next !== conf)    return setMsg({ tone:'err', text:'A confirmação não confere com a nova senha.' });
    setSaving(true);
    try {
      await window.DB.changePassword(needsCurrent ? curr : '', next);
      setMsg({ tone:'ok', text: needsCurrent ? 'Senha alterada com sucesso.' : 'Senha definida com sucesso. Agora você pode entrar com e-mail e senha também.' });
      setCurr(''); setNext(''); setConf('');
      // Atualiza flag hasPassword localmente pra esconder o aviso
      await window.DB.loadSession();
    } catch (e) {
      setMsg({ tone:'err', text: e.message });
    } finally {
      setSaving(false);
    }
  };

  return (
    <Card title="Segurança" desc={needsCurrent ? 'Trocar sua senha.' : 'Defina uma senha para a sua conta.'}>
      {!needsCurrent && (
        <div style={{
          padding:'12px 14px', background:'var(--bg-warm)', border:'1px solid var(--line)',
          borderRadius: 10, fontSize: 13, color:'var(--ink-2)', marginBottom: 16,
        }}>
          Você entrou com Google. Ainda não tem senha nesta conta — defina uma abaixo para poder entrar com e-mail e senha também.
        </div>
      )}

      <form onSubmit={submit}>
        {needsCurrent && (
          <Row label="Senha atual">
            <input type="password" value={curr} onChange={e => setCurr(e.target.value)} style={input} autoComplete="current-password"/>
          </Row>
        )}
        <Row label="Nova senha">
          <input type="password" value={next} onChange={e => setNext(e.target.value)} style={input} autoComplete="new-password" placeholder="Mínimo 6 caracteres"/>
        </Row>
        <Row label="Confirmar nova senha">
          <input type="password" value={conf} onChange={e => setConf(e.target.value)} style={input} autoComplete="new-password"/>
        </Row>

        {msg && <Msg {...msg}/>}

        <Button type="submit" variant="primary" size="lg" disabled={saving}>
          {saving ? 'Salvando…' : needsCurrent ? 'Trocar senha' : 'Definir senha'}
        </Button>
      </form>
    </Card>
  );
}

// ── Componentes auxiliares ────────────────────────────────────────────────
function Card({ title, desc, children }) {
  return (
    <div className="m-card-pad" style={{
      background:'var(--paper)', border:'1px solid var(--line)', borderRadius: 16,
      padding: 28, boxShadow:'var(--shadow-sm)',
    }}>
      <h2 className="serif m-h3" style={{ fontSize: 28, margin:'0 0 4px', letterSpacing:'-0.01em' }}>{title}</h2>
      {desc && <p style={{ fontSize: 14, color:'var(--ink-3)', margin:'0 0 22px' }}>{desc}</p>}
      {children}
    </div>
  );
}

function Row({ label, children }) {
  return (
    <label style={{ display:'block', marginBottom: 14 }}>
      <div style={{ fontSize: 13, fontWeight: 500, color:'var(--ink-2)', marginBottom: 6 }}>{label}</div>
      {children}
    </label>
  );
}

function Msg({ tone, text }) {
  const styles = tone === 'ok'
    ? { bg:'#EAF2E4', fg:'#5C6B3F', bd:'var(--olive)' }
    : { bg:'#FDECE7', fg:'#7A2E18', bd:'#E8B7A5' };
  return (
    <div style={{
      padding:'10px 14px', background: styles.bg, border:`1px solid ${styles.bd}`,
      color: styles.fg, borderRadius: 10, fontSize: 13, marginBottom: 14,
    }}>{text}</div>
  );
}

const input = {
  width:'100%', padding:'13px 14px', borderRadius: 12,
  border:'1px solid var(--line-2)', background:'var(--paper)',
  fontSize: 16, color:'var(--ink)', outline:'none',
  minHeight: 46,
};

Object.assign(window, { Account });
