/* global React, Card, Badge, Button, Avatar, Icon, ICONS, Field, sb, GoogleIntegrationSettings */
const { useState, useEffect, useRef, useCallback } = React;

// ─── AvatarCropModal ─────────────────────────────────────────────────────────
function AvatarCropModal({ onClose, onSave }) {
  const fileRef    = useRef(null);
  const canvasRef  = useRef(null);
  const [imgSrc,   setImgSrc]   = useState(null);
  const [imgEl,    setImgEl]    = useState(null);
  const [zoom,     setZoom]     = useState(1);
  const [offset,   setOffset]   = useState({ x: 0, y: 0 });
  const [dragging, setDragging] = useState(false);
  const [dragStart,setDragStart]= useState(null);
  const [uploading,setUploading]= useState(false);
  const SIZE = 280;

  function onFileChange(e) {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = ev => setImgSrc(ev.target.result);
    reader.readAsDataURL(file);
  }

  useEffect(() => {
    if (!imgSrc) return;
    const img = new Image();
    img.onload = () => {
      setImgEl(img);
      setZoom(1);
      setOffset({ x: 0, y: 0 });
    };
    img.src = imgSrc;
  }, [imgSrc]);

  const draw = useCallback(() => {
    const canvas = canvasRef.current;
    if (!canvas || !imgEl) return;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, SIZE, SIZE);

    // clip to circle
    ctx.save();
    ctx.beginPath();
    ctx.arc(SIZE/2, SIZE/2, SIZE/2, 0, Math.PI*2);
    ctx.clip();

    const scale = zoom * Math.max(SIZE / imgEl.width, SIZE / imgEl.height);
    const drawW = imgEl.width  * scale;
    const drawH = imgEl.height * scale;
    const x = (SIZE - drawW) / 2 + offset.x;
    const y = (SIZE - drawH) / 2 + offset.y;

    ctx.drawImage(imgEl, x, y, drawW, drawH);
    ctx.restore();

    // ring overlay
    ctx.beginPath();
    ctx.arc(SIZE/2, SIZE/2, SIZE/2 - 1, 0, Math.PI*2);
    ctx.strokeStyle = 'rgba(255,255,255,0.25)';
    ctx.lineWidth = 2;
    ctx.stroke();
  }, [imgEl, zoom, offset]);

  useEffect(() => { draw(); }, [draw]);

  function onPointerDown(e) {
    setDragging(true);
    setDragStart({ x: e.clientX - offset.x, y: e.clientY - offset.y });
    e.currentTarget.setPointerCapture(e.pointerId);
  }
  function onPointerMove(e) {
    if (!dragging || !dragStart) return;
    setOffset({ x: e.clientX - dragStart.x, y: e.clientY - dragStart.y });
  }
  function onPointerUp() { setDragging(false); }

  const [uploadError, setUploadError] = useState(null);

  async function handleSave() {
    const canvas = canvasRef.current;
    if (!canvas || !imgEl) return;
    setUploading(true);
    setUploadError(null);
    try {
      // Use data URL — no Storage bucket required
      const dataUrl = canvas.toDataURL('image/jpeg', 0.82);

      const { data: authData, error: authErr } = await sb.auth.getUser();
      if (authErr || !authData?.user) throw new Error('Sessão expirada — faça login novamente');

      const { error: dbErr } = await sb.from('profiles')
        .update({ avatar_url: dataUrl })
        .eq('id', authData.user.id);

      if (dbErr) {
        console.error('[avatar db]', dbErr);
        throw new Error(dbErr.message);
      }

      onSave(dataUrl);
    } catch (err) {
      console.error('[avatar save]', err);
      setUploadError(err.message || 'Erro desconhecido ao salvar foto');
    }
    setUploading(false);
  }

  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, background:'rgba(8,12,28,0.72)', backdropFilter:'blur(6px)',
      zIndex:300, display:'flex', alignItems:'center', justifyContent:'center', padding:24,
    }}>
      <div onClick={e=>e.stopPropagation()} style={{
        width:380, background:'var(--bg-surface)', border:'1px solid var(--border-subtle)',
        borderRadius:18, boxShadow:'0 28px 72px rgba(0,0,0,0.55)',
        display:'flex', flexDirection:'column', overflow:'hidden',
      }}>
        {/* Header */}
        <div style={{ padding:'18px 22px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <h3 style={{ margin:0, fontSize:17, fontWeight:700 }}>Foto de perfil</h3>
          <button onClick={onClose} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:6 }}>
            <Icon d={ICONS.x} size={17}/>
          </button>
        </div>

        {/* Body */}
        <div style={{ padding:'24px 22px', display:'flex', flexDirection:'column', alignItems:'center', gap:20 }}>
          {!imgSrc ? (
            <label
              htmlFor="avatar-file-input"
              style={{
                width: SIZE, height: SIZE, borderRadius:'50%', cursor:'pointer',
                border:'2px dashed var(--border-strong)',
                background:'var(--bg-elevated)',
                display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:10,
                color:'var(--fg-muted)',
              }}
            >
              <svg width={40} height={40} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>
              </svg>
              <span style={{ fontSize:13, fontWeight:600 }}>Clique para escolher</span>
              <span style={{ fontSize:11 }}>JPG, PNG ou WebP · máx 2 MB</span>
            </label>
          ) : (
            <>
              <div style={{ position:'relative', width:SIZE, height:SIZE, borderRadius:'50%', overflow:'hidden', cursor:dragging?'grabbing':'grab', userSelect:'none' }}>
                <canvas
                  ref={canvasRef}
                  width={SIZE}
                  height={SIZE}
                  style={{ display:'block', touchAction:'none' }}
                  onPointerDown={onPointerDown}
                  onPointerMove={onPointerMove}
                  onPointerUp={onPointerUp}
                />
              </div>
              <div style={{ width:'100%' }}>
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:8 }}>
                  <span style={{ fontSize:12, fontWeight:600, color:'var(--fg-muted)' }}>Zoom</span>
                  <span style={{ fontSize:11, color:'var(--fg-muted)', fontFamily:'var(--font-mono)' }}>{zoom.toFixed(1)}×</span>
                </div>
                <input
                  type="range" min={1} max={3} step={0.05} value={zoom}
                  onChange={e => setZoom(Number(e.target.value))}
                  style={{ width:'100%', accentColor:'var(--primary)', cursor:'pointer' }}
                />
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:10, color:'var(--fg-muted)', marginTop:4 }}>
                  <span>1×</span><span>Arraste para reposicionar</span><span>3×</span>
                </div>
              </div>
              <button
                onClick={() => { setImgSrc(null); setImgEl(null); fileRef.current.value=''; }}
                style={{ background:'transparent', border:'none', color:'var(--fg-muted)', fontSize:12, cursor:'pointer', textDecoration:'underline' }}
              >Escolher outra imagem</button>
            </>
          )}
        </div>

        {/* Error banner */}
        {uploadError && (
          <div style={{ margin:'0 22px 0', padding:'10px 14px', borderRadius:8, background:'rgba(239,68,68,0.12)', border:'1px solid rgba(239,68,68,0.35)', color:'#FCA5A5', fontSize:12, lineHeight:1.5 }}>
            <strong style={{ display:'block', marginBottom:2 }}>Erro ao enviar</strong>
            {uploadError}
          </div>
        )}

        {/* Footer */}
        <div style={{ padding:'14px 22px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'flex-end', gap:10 }}>
          <Button variant="secondary" onClick={onClose}>Cancelar</Button>
          <Button onClick={handleSave} style={{ opacity: (!imgEl||uploading)?0.5:1, pointerEvents:(!imgEl||uploading)?'none':'auto' }}>
            {uploading ? 'Enviando…' : 'Salvar foto'}
          </Button>
        </div>
        <input id="avatar-file-input" ref={fileRef} type="file" accept="image/jpeg,image/png,image/webp" style={{ display:'none' }} onChange={onFileChange}/>
      </div>
    </div>
  );
}

function ModalShell({ children, onClose, width = 640, title, subtitle, foot }) {
  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, background:'rgba(8,12,28,0.65)', backdropFilter:'blur(6px)',
      zIndex:200, display:'flex', alignItems:'center', justifyContent:'center', padding:24,
    }}>
      <div onClick={e=>e.stopPropagation()} style={{
        width:'100%', maxWidth:width, maxHeight:'90vh', display:'flex', flexDirection:'column',
        background:'var(--bg-surface)', border:'1px solid var(--border-subtle)', borderRadius:16,
        boxShadow:'0 24px 64px rgba(0,0,0,0.45)', overflow:'hidden',
      }}>
        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:14 }}>
          <div>
            {subtitle && <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--geek-blue-300)' }}>{subtitle}</div>}
            <h2 style={{ margin:'4px 0 0', fontSize:20, fontWeight:700 }}>{title}</h2>
          </div>
          <button onClick={onClose} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:6 }}>
            <Icon d={ICONS.x} size={18}/>
          </button>
        </div>
        <div style={{ flex:1, overflow:'auto' }}>{children}</div>
        {foot && <div style={{ padding:'14px 24px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'flex-end', gap:10 }}>{foot}</div>}
      </div>
    </div>
  );
}

// ─── Cakto checkout URLs ─────────────────────────────────────────────────────
const CAKTO_URL_MENSAL  = 'https://pay.cakto.com.br/38vm695_679341';
const CAKTO_URL_ANUAL   = 'https://pay.cakto.com.br/8rc3cre_887861';
const CAKTO_PORTAL_URL  = 'https://app.cakto.com.br/minha-conta';

const FOUNDERS_FEATURES = [
  'Projetos e clientes ilimitados',
  'Financeiro completo (receitas, despesas, fluxo)',
  'Orçamentos e briefings',
  'Calendário + Google Calendar & Meet',
  'Google Drive integrado',
  'Grid de preview de feed',
  'Páginas públicas e portfólios',
  'Relatórios e métricas',
  'Todas as funcionalidades atuais',
  'Todas as atualizações futuras incluídas',
];

function AssinaturaModal({ onClose, subStatus, subExpires, subPeriod }) {
  const isActive = subStatus === 'active';
  const fmtDate = (iso) => {
    if (!iso) return '—';
    try { return new Date(iso).toLocaleDateString('pt-BR'); } catch { return iso; }
  };

  if (isActive) {
    return (
      <ModalShell title="Sua assinatura" subtitle="Plano Fundadores" onClose={onClose} width={520}
        foot={<Button variant="secondary" onClick={onClose}>Fechar</Button>}>
        <div style={{ padding:24 }}>
          <div style={{ display:'flex', alignItems:'center', gap:14, padding:'18px 20px', borderRadius:14, background:'linear-gradient(135deg,rgba(34,197,94,0.12),rgba(34,197,94,0.04))', border:'1px solid rgba(34,197,94,0.3)', marginBottom:20 }}>
            <div style={{ width:46, height:46, borderRadius:12, background:'rgba(34,197,94,0.2)', display:'grid', placeItems:'center', flexShrink:0 }}>
              <svg width={22} height={22} viewBox="0 0 24 24" fill="none" stroke="#22C55E" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
            </div>
            <div>
              <div style={{ fontSize:15, fontWeight:700, color:'#22C55E' }}>Assinatura ativa</div>
              <div style={{ fontSize:12, color:'var(--fg-secondary)', marginTop:2 }}>Plano Fundadores · Mensal</div>
            </div>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:20 }}>
            <div style={{ background:'var(--bg-elevated)', borderRadius:10, padding:'14px 16px' }}>
              <div style={{ fontSize:11, color:'var(--fg-muted)', fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em' }}>Próxima cobrança</div>
              <div style={{ fontSize:16, fontWeight:700, marginTop:4 }}>{fmtDate(subExpires)}</div>
            </div>
            <div style={{ background:'var(--bg-elevated)', borderRadius:10, padding:'14px 16px' }}>
              <div style={{ fontSize:11, color:'var(--fg-muted)', fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em' }}>Valor</div>
              <div style={{ fontSize:16, fontWeight:700, marginTop:4 }}>{subPeriod === 'annual' ? 'R$397/ano' : 'R$47/mês'}</div>
            </div>
          </div>
          {subPeriod !== 'annual' && (
            <a href={CAKTO_URL_ANUAL} target="_blank" rel="noopener noreferrer"
              style={{ display:'flex', alignItems:'center', justifyContent:'space-between', width:'100%', padding:'12px 16px', borderRadius:10, border:'1px solid rgba(250,173,20,0.35)', background:'rgba(250,173,20,0.08)', textDecoration:'none', boxSizing:'border-box', marginBottom:10 }}>
              <div>
                <div style={{ fontSize:13, fontWeight:700, color:'#FAAD14' }}>Migrar para plano anual</div>
                <div style={{ fontSize:11, color:'var(--fg-secondary)', marginTop:2 }}>R$397/ano · economize R$167 · ≈ R$33/mês</div>
              </div>
              <svg width={14} height={14} viewBox="0 0 24 24" fill="none" stroke="#FAAD14" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
            </a>
          )}
          <a href={CAKTO_PORTAL_URL} target="_blank" rel="noopener noreferrer"
            style={{ display:'flex', alignItems:'center', justifyContent:'center', gap:8, width:'100%', padding:'11px 0', borderRadius:10, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-secondary)', fontSize:13, fontWeight:600, textDecoration:'none', boxSizing:'border-box' }}>
            Gerenciar assinatura no Cakto
            <svg width={13} height={13} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
          </a>
          <p style={{ margin:'14px 0 0', fontSize:11, color:'var(--fg-muted)', textAlign:'center' }}>Cancelamento pode ser feito a qualquer momento no portal do Cakto. Acesso mantido até o fim do período pago.</p>
        </div>
      </ModalShell>
    );
  }

  return (
    <ModalShell title="Plano Fundadores" subtitle="Acesso completo ao inBrivvo" onClose={onClose} width={620}
      foot={<Button variant="secondary" onClick={onClose}>Fechar</Button>}>
      <div style={{ padding:24 }}>
        {/* Header do plano */}
        <div style={{ padding:'20px 22px', borderRadius:14, background:'linear-gradient(135deg,rgba(29,57,196,0.15),rgba(29,57,196,0.04))', border:'1px solid var(--geek-blue-a40)', marginBottom:20 }}>
          <div style={{ display:'flex', alignItems:'baseline', gap:10, flexWrap:'wrap' }}>
            <span style={{ fontFamily:'var(--font-display)', fontSize:32, fontWeight:800, color:'var(--geek-blue-200)', letterSpacing:'-0.02em' }}>R$47</span>
            <span style={{ fontSize:15, color:'var(--fg-secondary)' }}>/mês</span>
          </div>
          <div style={{ marginTop:10, display:'inline-flex', alignItems:'center', gap:6, padding:'4px 12px', borderRadius:999, background:'rgba(250,173,20,0.15)', border:'1px solid rgba(250,173,20,0.35)', fontSize:11, fontWeight:700, color:'#FAAD14', letterSpacing:'0.04em', textTransform:'uppercase' }}>
            ⭐ Preço de Fundadores — vai aumentar com o produto
          </div>
          <p style={{ margin:'12px 0 0', fontSize:13, color:'var(--fg-secondary)', lineHeight:1.6 }}>
            Acesso completo a todas as funcionalidades. Quem assinar agora garante esse preço para sempre, mesmo quando aumentar.
          </p>
        </div>

        {/* Features */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'8px 16px', marginBottom:22 }}>
          {FOUNDERS_FEATURES.map(f => (
            <div key={f} style={{ display:'flex', alignItems:'center', gap:8, fontSize:12, color:'var(--fg-secondary)' }}>
              <span style={{ width:16, height:16, borderRadius:'50%', background:'rgba(34,197,94,0.2)', border:'1px solid rgba(34,197,94,0.4)', display:'grid', placeItems:'center', flexShrink:0 }}>
                <svg width="8" height="8" viewBox="0 0 8 8"><path d="M1 4l2 2 4-4" stroke="#22C55E" strokeWidth="1.5" fill="none" strokeLinecap="round"/></svg>
              </span>
              {f}
            </div>
          ))}
        </div>

        {/* CTA */}
        <a href={CAKTO_URL_MENSAL} target="_blank" rel="noopener noreferrer"
          style={{ display:'flex', alignItems:'center', justifyContent:'center', gap:10, padding:'15px 24px', borderRadius:12, background:'var(--primary)', textDecoration:'none', cursor:'pointer' }}>
          <svg width={16} height={16} viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
          <div style={{ fontSize:15, fontWeight:800, color:'#fff' }}>Assinar agora — R$47/mês</div>
        </a>
        <p style={{ margin:'12px 0 0', fontSize:11, color:'var(--fg-muted)', textAlign:'center' }}>Pagamento seguro via Cakto · PIX, cartão de crédito e boleto · cancele quando quiser</p>
      </div>
    </ModalShell>
  );
}

function HistoricoFaturasModal({ onClose }) {
  const faturas = [
    { id:'INV-0024', data:'22/04/2026', desc:'Premium · Abr 2026',  valor:'R$ 89,00', status:'Pago' },
    { id:'INV-0023', data:'22/03/2026', desc:'Premium · Mar 2026',  valor:'R$ 89,00', status:'Pago' },
    { id:'INV-0022', data:'22/02/2026', desc:'Premium · Fev 2026',  valor:'R$ 89,00', status:'Pago' },
    { id:'INV-0021', data:'22/01/2026', desc:'Premium · Jan 2026',  valor:'R$ 89,00', status:'Pago' },
    { id:'INV-0020', data:'22/12/2025', desc:'Premium · Dez 2025',  valor:'R$ 89,00', status:'Pago' },
    { id:'INV-0019', data:'22/11/2025', desc:'Premium · Nov 2025',  valor:'R$ 89,00', status:'Pago' },
    { id:'INV-0018', data:'22/10/2025', desc:'Pro · Out 2025',      valor:'R$ 49,00', status:'Pago' },
    { id:'INV-0017', data:'22/09/2025', desc:'Pro · Set 2025',      valor:'R$ 49,00', status:'Pago' },
  ];
  return (
    <ModalShell title="Histórico de faturas" subtitle="Plano & cobrança" onClose={onClose} width={620}
      foot={<Button variant="secondary" onClick={onClose}>Fechar</Button>}>
      <div style={{ padding:'0 24px 24px' }}>
        <div style={{ display:'grid', gridTemplateColumns:'100px 1fr 1fr 90px 44px', gap:0, padding:'12px 0', borderBottom:'1px solid var(--border-subtle)', marginTop:20 }}>
          {['Nº Fatura','Descrição','Data','Valor',''].map(h => (
            <div key={h} style={{ fontSize:11, fontWeight:700, color:'var(--fg-muted)', textTransform:'uppercase', letterSpacing:'0.06em' }}>{h}</div>
          ))}
        </div>
        {faturas.map((f, i) => (
          <div key={f.id} style={{ display:'grid', gridTemplateColumns:'100px 1fr 1fr 90px 44px', alignItems:'center', padding:'13px 0', borderBottom: i < faturas.length-1 ? '1px solid var(--border-subtle)' : 'none' }}>
            <span style={{ fontSize:12, color:'var(--fg-muted)', fontFamily:'var(--font-display)' }}>{f.id}</span>
            <span style={{ fontSize:13 }}>{f.desc}</span>
            <span style={{ fontSize:12, color:'var(--fg-secondary)' }}>{f.data}</span>
            <span style={{ fontSize:13, fontWeight:600 }}>{f.valor}</span>
            <button onClick={()=>window.__toast?.(`${f.id} baixado`,{tone:'success'})} style={{ background:'transparent', border:'1px solid var(--border-subtle)', borderRadius:6, cursor:'pointer', color:'var(--fg-secondary)', padding:'4px 8px', fontSize:11, fontFamily:'inherit' }}>PDF</button>
          </div>
        ))}
      </div>
    </ModalShell>
  );
}

const APP_DEFAULTS = { primary:'#1D39C4', secondary:'#2F54EB', accent:'#22C55E', sidebar:'#0D121A', background:'#121A26', text:'#E6ECF8' };
const APP_PRESETS = {
  'Azul (padrão)': { ...APP_DEFAULTS },
  'Laranja':       { primary:'#FF8A3D', secondary:'#E55F00', accent:'#10B981', sidebar:'#0E1621', background:'#121A25', text:'#F8FAFC' },
  'Roxo':          { primary:'#7C3AED', secondary:'#6D28D9', accent:'#22C55E', sidebar:'#0D0A1A', background:'#130F26', text:'#EDE9FE' },
  'Verde':         { primary:'#16A34A', secondary:'#15803D', accent:'#3B82F6', sidebar:'#0A1A0E', background:'#0F1F14', text:'#DCFCE7' },
};
function activePresetName(colors) {
  for (const [name, p] of Object.entries(APP_PRESETS)) {
    if (Object.keys(p).every(k => (colors[k]||'').toLowerCase() === (p[k]||'').toLowerCase())) return name;
  }
  return 'Personalizado';
}

// ─── Google Integration Helpers (inline — no external file dependency) ────────
const GS_SCOPES = {
  CALENDAR: 'https://www.googleapis.com/auth/calendar',
  DRIVE:    'https://www.googleapis.com/auth/drive.file',
};
const GS_SETTINGS_KEY = 'inbrivvo_google_settings';

async function gsGetToken() {
  try {
    const { data } = await sb.auth.getSession();
    return data?.session?.provider_token || null;
  } catch { return null; }
}

async function gsRequestScopes(scopesArray) {
  const base = 'openid email profile';
  const all  = [base, ...scopesArray].join(' ');
  await sb.auth.signInWithOAuth({
    provider: 'google',
    options: {
      redirectTo: window.location.origin + window.location.pathname,
      scopes: all,
      queryParams: { access_type: 'offline', prompt: 'consent' },
    },
  });
}

function useGSSettings() {
  const stored = (() => { try { return JSON.parse(localStorage.getItem(GS_SETTINGS_KEY) || '{}'); } catch { return {}; } })();
  const [s, setS] = useState({ calendarEnabled: false, meetEnabled: false, driveEnabled: false, ...stored });
  function update(key, val) {
    setS(prev => {
      const next = { ...prev, [key]: val };
      localStorage.setItem(GS_SETTINGS_KEY, JSON.stringify(next));
      return next;
    });
  }
  return [s, update];
}

function GoogleIntegrationSettings({ onClose }) {
  const [settings, updateSetting] = useGSSettings();
  const [hasToken, setHasToken]   = useState(null);

  useEffect(() => {
    gsGetToken().then(tok => setHasToken(!!tok));
  }, []);

  async function handleToggle(key, scopeKey) {
    const want = !settings[key];
    if (want && !hasToken) {
      await gsRequestScopes([GS_SCOPES[scopeKey]]);
      return;
    }
    updateSetting(key, want);
  }

  const CARDS = [
    { key: 'calendarEnabled', scopeKey: 'CALENDAR', emoji: '📅', title: 'Google Calendar', desc: 'Crie e sincronize eventos da agenda com seu Google Calendar.' },
    { key: 'meetEnabled',     scopeKey: 'CALENDAR', emoji: '📹', title: 'Google Meet',     desc: 'Gere links de Meet automaticamente ao criar reuniões no app.' },
    { key: 'driveEnabled',    scopeKey: 'DRIVE',    emoji: '🗂',  title: 'Google Drive',   desc: 'Envie arquivos de projeto para o Google Drive automaticamente.' },
  ];

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(8,12,28,0.65)', backdropFilter:'blur(6px)', zIndex:400, display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
      <div onClick={e=>e.stopPropagation()} style={{ width:'min(520px,100%)', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:16, boxShadow:'0 24px 64px rgba(0,0,0,0.5)', overflow:'hidden' }}>
        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:12 }}>
          <div style={{ width:42, height:42, borderRadius:10, background:'linear-gradient(135deg,#4285F4,#34A853)', display:'grid', placeItems:'center', color:'#fff', fontWeight:900, fontSize:22, flexShrink:0 }}>G</div>
          <div style={{ flex:1 }}>
            <h2 style={{ margin:0, fontSize:17, fontWeight:700 }}>Integrações Google</h2>
            <p style={{ margin:'2px 0 0', fontSize:12, color:'var(--fg-muted)' }}>Conecte Calendar, Meet e Drive ao inBrivvo.</p>
          </div>
          <button onClick={onClose} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', fontSize:22, lineHeight:1, padding:4 }}>×</button>
        </div>
        <div style={{ padding:20, display:'flex', flexDirection:'column', gap:10 }}>
          {hasToken === false && (
            <div style={{ padding:'12px 16px', borderRadius:10, background:'rgba(250,173,20,0.1)', border:'1px solid rgba(250,173,20,0.3)', fontSize:13, color:'var(--fg-secondary)', marginBottom:2 }}>
              Conta Google não conectada. Ative uma opção abaixo para iniciar a autenticação.
            </div>
          )}
          {CARDS.map(card => (
            <div key={card.key} style={{ display:'flex', alignItems:'center', gap:14, padding:'14px 16px', borderRadius:12, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)' }}>
              <span style={{ fontSize:26, flexShrink:0 }}>{card.emoji}</span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:14, fontWeight:600 }}>{card.title}</div>
                <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:3, lineHeight:1.4 }}>{card.desc}</div>
              </div>
              <button
                type="button"
                onClick={() => handleToggle(card.key, card.scopeKey)}
                disabled={hasToken === null}
                style={{ width:44, height:24, borderRadius:12, border:'none', cursor: hasToken === null ? 'default' : 'pointer', background: settings[card.key] ? '#22C55E' : 'var(--border-strong)', position:'relative', transition:'background 200ms', flexShrink:0, opacity: hasToken === null ? 0.5 : 1 }}
              >
                <span style={{ position:'absolute', top:3, left: settings[card.key] ? 'calc(100% - 21px)' : 3, width:18, height:18, borderRadius:'50%', background:'#fff', transition:'left 200ms', boxShadow:'0 1px 4px rgba(0,0,0,0.3)' }}/>
              </button>
            </div>
          ))}
          {hasToken === false && (
            <Button onClick={() => gsRequestScopes([GS_SCOPES.CALENDAR, GS_SCOPES.DRIVE])} style={{ width:'100%', justifyContent:'center', marginTop:6 }}>
              Conectar conta Google
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Settings ─────────────────────────────────────────────────────────────────
function Settings() {
  const [tab, setTab] = useState('perfil');
  const [modalPlano,   setModalPlano]   = useState(false);
  const [modalFaturas, setModalFaturas] = useState(false);
  const [cropModal,    setCropModal]    = useState(false);
  const [showGS,       setShowGS]       = useState(false);

  // Subscription state (lido do Supabase)
  const [subStatus,  setSubStatus]  = useState(null); // 'active' | 'inactive' | null
  const [subPlan,    setSubPlan]    = useState(null); // 'founders'
  const [subPeriod,  setSubPeriod]  = useState(null); // 'monthly' | 'annual'
  const [subExpires, setSubExpires] = useState(null); // ISO date string

  // Profile state
  const [profileName,  setProfileName]  = useState('');
  const [profileEmail, setProfileEmail] = useState('');
  const [profileRole,  setProfileRole]  = useState('');
  const [profilePhone, setProfilePhone] = useState('');
  const [studioName,   setStudioName]   = useState('');
  const [studioCnpj,   setStudioCnpj]   = useState('');
  const [studioCity,   setStudioCity]   = useState('');
  const [studioSite,   setStudioSite]   = useState('');
  const [profileId,    setProfileId]    = useState(null);
  const [avatarUrl,    setAvatarUrl]    = useState(null);
  const [saving,       setSaving]       = useState(false);
  const logoFileRef                     = useRef(null);
  const [appTheme,      setAppTheme]    = useState('dark');
  const [logoUrl,       setLogoUrl]     = useState(null);
  const [logoShowLogin, setLogoShowLogin] = useState(false);
  const [colors,        setColors]      = useState({ ...APP_DEFAULTS });

  useEffect(() => {
    (async () => {
      const { data: { user } } = await sb.auth.getUser();
      if (!user) return;
      setProfileId(user.id);
      setProfileEmail(user.email || '');
      const { data } = await sb.from('profiles').select('*').eq('id', user.id).single();
      if (data) {
        setProfileName(data.name || '');
        setStudioName(data.studio || '');
        setAvatarUrl(data.avatar_url || null);
        setProfileRole(data.role || '');
        setProfilePhone(data.phone || '');
        setStudioCnpj(data.cnpj || '');
        setStudioCity(data.city || '');
        setStudioSite(data.website || '');
        const app = data.appearance || {};
        setAppTheme(app.theme || 'dark');
        setLogoShowLogin(app.logoShowLogin || false);
        setLogoUrl(data.logo_url || null);
        setColors({
          primary:    app.primary    || APP_DEFAULTS.primary,
          secondary:  app.secondary  || APP_DEFAULTS.secondary,
          accent:     app.accent     || APP_DEFAULTS.accent,
          sidebar:    app.sidebar    || APP_DEFAULTS.sidebar,
          background: app.background || APP_DEFAULTS.background,
          text:       app.text       || APP_DEFAULTS.text,
        });
        // Subscription fields (adicionados via migração)
        setSubStatus(data.subscription_status || null);
        setSubPlan(data.subscription_plan || null);
        setSubPeriod(data.subscription_period || null);
        setSubExpires(data.subscription_expires_at || null);
      }
    })();
  }, []);

  async function saveProfile() {
    if (!profileId) return;
    setSaving(true);
    const { error } = await sb.from('profiles').update({
      name:    profileName,
      studio:  studioName,
      role:    profileRole,
      phone:   profilePhone,
      cnpj:    studioCnpj,
      city:    studioCity,
      website: studioSite,
    }).eq('id', profileId);
    setSaving(false);
    if (error) { window.__toast?.(error.message, { tone:'danger' }); }
    else { window.__toast?.('Alterações salvas', { tone:'success' }); }
  }

  function handleAvatarSaved(url) {
    setAvatarUrl(url);
    setCropModal(false);
    window.__toast?.('Foto de perfil atualizada', { tone:'success' });
    if (window.__onAvatarUpdate) window.__onAvatarUpdate(url);
  }

  function onLogoChange(e) {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = ev => setLogoUrl(ev.target.result);
    reader.readAsDataURL(file);
    e.target.value = '';
  }

  async function saveAppearance() {
    if (!profileId) {
      window.__toast?.('Sessão não carregada. Recarregue a página.', { tone:'danger' });
      return;
    }
    setSaving(true);
    const appearance = { theme: appTheme, logoShowLogin, ...colors };

    // Save appearance separately from logo_url to avoid issues with large base64 logos
    const updates = { appearance };
    if (logoUrl !== undefined) updates.logo_url = logoUrl;

    // Apply CSS vars immediately (optimistic update — don't wait for DB confirm)
    document.documentElement.setAttribute('data-theme', appTheme);
    document.body.className = `ds-root theme-${appTheme}`;
    document.documentElement.style.setProperty('--primary',        colors.primary);
    document.documentElement.style.setProperty('--primary-hover',  colors.secondary);
    document.documentElement.style.setProperty('--accent-success', colors.accent);
    document.documentElement.style.setProperty('--bg-app',         colors.sidebar);
    document.documentElement.style.setProperty('--bg-surface',     colors.background);
    document.documentElement.style.setProperty('--fg-primary',     colors.text);
    // Sync saved appearance so tweaks effect doesn't override it
    window.__savedAppearance = { ...colors, theme: appTheme };
    if (window.__setTheme) window.__setTheme(appTheme);

    const { error } = await sb.from('profiles')
      .update(updates)
      .eq('id', profileId);

    if (error) {
      console.error('[inBrivvo] saveAppearance error:', error);
      window.__toast?.(error.message || 'Erro ao salvar aparência', { tone:'danger' });
    } else {
      window.__toast?.('Aparência salva com sucesso!', { tone:'success' });
    }
    setSaving(false);
  }

  function restoreDefaults() {
    setColors({ ...APP_DEFAULTS });
    setAppTheme('dark');
    setLogoShowLogin(false);
  }

  const pvSidebar = appTheme === 'light' ? '#F1F3F7' : colors.sidebar;
  const pvBg      = appTheme === 'light' ? '#FFFFFF' : colors.background;
  const pvText    = appTheme === 'light' ? '#1C1F26' : colors.text;
  const pvBorder  = appTheme === 'light' ? 'rgba(0,0,0,0.08)' : 'rgba(255,255,255,0.07)';

  const tabs = [
    { id:'perfil',     l:'Perfil' },
    { id:'org',        l:'Organização' },
    { id:'team',       l:'Equipe & papéis' },
    { id:'aparencia',  l:'Aparência' },
    { id:'integ',      l:'Integrações' },
    { id:'plano',      l:'Plano & cobrança' },
    { id:'notif',      l:'Notificações' },
    { id:'legal',      l:'Documentos legais' },
  ];
  return (
    <>
    <div style={{ padding:'24px 28px', display:'grid', gridTemplateColumns:'220px 1fr', gap:22 }}>
      <Card padding={10}>
        {tabs.map(t => (
          <div key={t.id} onClick={()=>setTab(t.id)} style={{
            padding:'10px 12px', borderRadius:8, cursor:'pointer',
            background: tab===t.id ? 'var(--primary-soft)':'transparent',
            color: tab===t.id ? 'var(--geek-blue-200)':'var(--fg-secondary)',
            fontSize:13, fontWeight:tab===t.id?600:500,
          }}>{t.l}</div>
        ))}
      </Card>

      <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
        {tab==='perfil' && (
          <Card padding={24}>
            <h3 style={{ margin:0, fontSize:18, fontWeight:700 }}>Perfil</h3>
            <p style={{ color:'var(--fg-muted)', fontSize:13, marginTop:4 }}>Informações que aparecem para sua equipe e clientes.</p>
            <div style={{ display:'flex', alignItems:'center', gap:18, marginTop:18, padding:18, borderRadius:12, background:'var(--bg-elevated)' }}>
              <div style={{ position:'relative', flexShrink:0 }}>
                <Avatar name={profileName || 'U'} size={72} src={avatarUrl}/>
                <button
                  onClick={()=>setCropModal(true)}
                  title="Trocar foto"
                  style={{
                    position:'absolute', bottom:0, right:0,
                    width:26, height:26, borderRadius:'50%',
                    background:'var(--primary)', border:'2px solid var(--bg-surface)',
                    color:'#fff', cursor:'pointer', display:'grid', placeItems:'center',
                    padding:0,
                  }}
                >
                  <svg width={13} height={13} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round">
                    <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
                    <circle cx="12" cy="13" r="4"/>
                  </svg>
                </button>
              </div>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:15, fontWeight:700 }}>{profileName || '—'}</div>
                <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:3 }}>{profileRole || 'Membro'} · {studioName || '—'}</div>
                <button
                  onClick={()=>setCropModal(true)}
                  style={{ marginTop:8, background:'transparent', border:'1px solid var(--border-strong)', borderRadius:6, padding:'5px 12px', fontSize:12, fontWeight:600, color:'var(--fg-secondary)', cursor:'pointer', fontFamily:'inherit' }}
                >Trocar foto</button>
              </div>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginTop:18 }}>
              <Field label="Nome completo" value={profileName} onChange={e=>setProfileName(e.target.value)}/>
              <Field label="E-mail" value={profileEmail} onChange={e=>setProfileEmail(e.target.value)}/>
              <Field label="Cargo" value={profileRole} onChange={e=>setProfileRole(e.target.value)}/>
              <Field label="Telefone" value={profilePhone} onChange={e=>setProfilePhone(e.target.value)}/>
            </div>
            <div style={{ display:'flex', justifyContent:'flex-end', gap:10, marginTop:18 }}>
              <Button variant="secondary" onClick={()=>window.__toast?.('Alterações descartadas')}>Cancelar</Button>
              <Button onClick={saveProfile} style={{ opacity:saving?0.6:1, pointerEvents:saving?'none':'auto' }}>{saving?'Salvando…':'Salvar alterações'}</Button>
            </div>
          </Card>
        )}

        {tab==='aparencia' && (
          <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:18, alignItems:'start' }}>

              {/* LEFT: Live Preview */}
              <Card padding={20}>
                <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:14 }}>
                  <svg width={15} height={15} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>
                  </svg>
                  <span style={{ fontSize:14, fontWeight:700 }}>Pré-visualização</span>
                </div>
                <div style={{ background:pvSidebar, borderRadius:12, padding:'16px 12px' }}>
                  <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:16, paddingBottom:12, borderBottom:`1px solid ${pvBorder}` }}>
                    {logoUrl
                      ? <img src={logoUrl} style={{ height:26, maxWidth:80, objectFit:'contain' }} alt="logo"/>
                      : <div style={{ width:26, height:26, borderRadius:7, background:colors.primary, display:'grid', placeItems:'center', flexShrink:0 }}>
                          <span style={{ color:'#fff', fontWeight:800, fontSize:11 }}>in</span>
                        </div>
                    }
                    <span style={{ color:pvText, fontWeight:700, fontSize:13 }}>inBrivvo</span>
                  </div>
                  {['Dashboard','Projetos','Clientes','Financeiro'].map((item,i) => (
                    <div key={item} style={{
                      padding:'6px 10px', borderRadius:7, marginBottom:3,
                      background: i===0 ? colors.primary+'28' : 'transparent',
                      color: i===0 ? colors.primary : pvText+'88',
                      fontSize:12, fontWeight: i===0 ? 600 : 400,
                      display:'flex', alignItems:'center', gap:8,
                    }}>
                      <span style={{ width:5, height:5, borderRadius:'50%', background: i===0?colors.primary:'currentColor', opacity:0.5, flexShrink:0 }}/>
                      {item}
                    </div>
                  ))}
                  <div style={{ marginTop:12, background:pvBg, borderRadius:10, padding:12, border:`1px solid ${pvBorder}` }}>
                    <div style={{ fontSize:9, color:pvText+'66', marginBottom:8, letterSpacing:'0.06em', fontWeight:700 }}>EXEMPLO DE CARD</div>
                    <div style={{ background:colors.primary, borderRadius:6, padding:'7px 0', color:'#fff', fontSize:11, fontWeight:600, textAlign:'center', marginBottom:10 }}>
                      Botão Primário
                    </div>
                    <div style={{ display:'flex', gap:3, alignItems:'flex-end', height:28 }}>
                      {[60,80,45,90,70,55,85].map((h,i) => (
                        <div key={i} style={{ flex:1, height:h+'%', background: i===3?colors.primary:colors.accent+'55', borderRadius:2 }}/>
                      ))}
                    </div>
                  </div>
                </div>
                <div style={{ marginTop:12, display:'flex', gap:8 }}>
                  {[['dark','Escuro'],['light','Claro']].map(([val,label]) => (
                    <button key={val} onClick={()=>setAppTheme(val)} style={{
                      flex:1, padding:'7px 0', borderRadius:8, cursor:'pointer', fontFamily:'inherit',
                      fontSize:12, fontWeight:600,
                      border: appTheme===val ? `2px solid ${colors.primary}` : '2px solid var(--border-subtle)',
                      background: appTheme===val ? colors.primary+'20' : 'var(--bg-elevated)',
                      color: appTheme===val ? colors.primary : 'var(--fg-secondary)',
                    }}>{label}</button>
                  ))}
                </div>
              </Card>

              {/* RIGHT: Logo + Colors */}
              <div style={{ display:'flex', flexDirection:'column', gap:18 }}>

                {/* Logo card */}
                <Card padding={20}>
                  <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:14 }}>
                    <svg width={15} height={15} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="16 16 12 12 8 16"/><line x1="12" y1="12" x2="12" y2="21"/>
                      <path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"/>
                    </svg>
                    <span style={{ fontSize:14, fontWeight:700 }}>Logo da Agência</span>
                  </div>
                  <div style={{ display:'flex', gap:14, alignItems:'flex-start' }}>
                    <div style={{ width:64, height:64, borderRadius:10, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', display:'grid', placeItems:'center', overflow:'hidden', flexShrink:0 }}>
                      {logoUrl
                        ? <img src={logoUrl} style={{ maxWidth:'100%', maxHeight:'100%', objectFit:'contain' }} alt="logo"/>
                        : <svg width={22} height={22} viewBox="0 0 24 24" fill="none" stroke="var(--fg-muted)" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
                            <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>
                          </svg>
                      }
                    </div>
                    <div style={{ flex:1 }}>
                      <label htmlFor="logo-file-input" style={{
                        display:'flex', alignItems:'center', justifyContent:'center', gap:8,
                        padding:'8px 14px', background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)',
                        borderRadius:8, cursor:'pointer', fontSize:12, fontWeight:600, color:'var(--fg-secondary)',
                      }}>
                        <svg width={13} height={13} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
                          <polyline points="16 16 12 12 8 16"/><line x1="12" y1="12" x2="12" y2="21"/>
                          <path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"/>
                        </svg>
                        Alterar Logo
                      </label>
                      <p style={{ fontSize:11, color:'var(--fg-muted)', margin:'6px 0 0' }}>Recomendado: 512×512px, fundo transparente</p>
                      {logoUrl && (
                        <button onClick={()=>setLogoUrl(null)} style={{ marginTop:6, background:'transparent', border:'none', color:'var(--accent-danger)', fontSize:11, cursor:'pointer', fontFamily:'inherit', padding:0 }}>Remover logo</button>
                      )}
                    </div>
                  </div>
                  <input id="logo-file-input" ref={logoFileRef} type="file" accept="image/*" style={{ display:'none' }} onChange={onLogoChange}/>
                  <div style={{ marginTop:14, display:'flex', alignItems:'center', justifyContent:'space-between', padding:'12px 14px', background:'var(--bg-elevated)', borderRadius:10 }}>
                    <div>
                      <div style={{ fontSize:13, fontWeight:600 }}>Exibir na tela de login</div>
                      <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:2 }}>Mostrar logo quando membros fizerem login</div>
                    </div>
                    <div onClick={()=>setLogoShowLogin(l=>!l)} style={{ width:36, height:20, borderRadius:999, background:logoShowLogin?colors.primary:'var(--bg-surface)', border:'1px solid var(--border-strong)', cursor:'pointer', position:'relative', flexShrink:0 }}>
                      <div style={{ position:'absolute', top:2, left:logoShowLogin?18:2, width:14, height:14, borderRadius:'50%', background:'#fff', transition:'left 180ms ease' }}/>
                    </div>
                  </div>
                </Card>

                {/* Colors card */}
                <Card padding={20}>
                  <div style={{ fontSize:14, fontWeight:700, marginBottom:14 }}>Esquema de Cores</div>
                  <div style={{ marginBottom:14 }}>
                    <div style={{ fontSize:11, fontWeight:700, color:'var(--fg-muted)', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:6 }}>Preset Visual</div>
                    <select
                      value={activePresetName(colors)}
                      onChange={e => { const p = APP_PRESETS[e.target.value]; if (p) setColors({...p}); }}
                      style={{ width:'100%', padding:'8px 12px', borderRadius:8, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-primary)', fontFamily:'inherit', fontSize:13, outline:'none', cursor:'pointer' }}
                    >
                      {Object.keys(APP_PRESETS).map(n => <option key={n} value={n}>{n}</option>)}
                      {activePresetName(colors)==='Personalizado' && <option value="Personalizado">Personalizado</option>}
                    </select>
                  </div>
                  {[
                    ['primary',    'Cor Primária'],
                    ['secondary',  'Cor Secundária'],
                    ['accent',     'Cor de Acento'],
                    ['sidebar',    'Cor da Sidebar'],
                    ['background', 'Cor de Fundo'],
                    ['text',       'Cor do Texto'],
                  ].map(([key, label]) => (
                    <div key={key} style={{ marginBottom:8 }}>
                      <div style={{ fontSize:11, fontWeight:600, color:'var(--fg-muted)', marginBottom:5 }}>{label}</div>
                      <div style={{ display:'flex', alignItems:'center', gap:8, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', borderRadius:8, padding:'5px 10px' }}>
                        <input
                          type="color"
                          value={colors[key]}
                          onChange={e => setColors(c => ({ ...c, [key]: e.target.value }))}
                          style={{ width:26, height:26, border:'none', padding:0, background:'none', cursor:'pointer', borderRadius:4, flexShrink:0 }}
                        />
                        <input
                          type="text"
                          value={colors[key]}
                          onChange={e => { const v = e.target.value; if (/^#[0-9A-Fa-f]{0,6}$/.test(v)) setColors(c => ({ ...c, [key]: v })); }}
                          style={{ flex:1, background:'none', border:'none', outline:'none', fontFamily:'var(--font-mono)', fontSize:12, color:'var(--fg-secondary)' }}
                          maxLength={7}
                        />
                      </div>
                    </div>
                  ))}
                </Card>

              </div>
            </div>

            {/* Footer */}
            <div style={{ display:'flex', justifyContent:'flex-end', gap:10 }}>
              <Button variant="secondary" onClick={restoreDefaults}>Restaurar Padrão</Button>
              <Button onClick={saveAppearance} style={{ opacity:saving?0.6:1, pointerEvents:saving?'none':'auto' }}>
                {saving ? 'Salvando…' : 'Salvar Alterações'}
              </Button>
            </div>
          </div>
        )}

        {tab==='org' && (
          <Card padding={24}>
            <h3 style={{ margin:0, fontSize:18, fontWeight:700 }}>Organização</h3>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginTop:18 }}>
              <Field label="Nome da organização" value={studioName} onChange={e=>setStudioName(e.target.value)}/>
              <Field label="CNPJ" value={studioCnpj} onChange={e=>setStudioCnpj(e.target.value)} placeholder="00.000.000/0001-00"/>
              <Field label="Cidade" value={studioCity} onChange={e=>setStudioCity(e.target.value)} placeholder="São Paulo · SP"/>
              <Field label="Site" value={studioSite} onChange={e=>setStudioSite(e.target.value)} placeholder="seusite.com.br"/>
            </div>
            <div style={{ display:'flex', justifyContent:'flex-end', marginTop:18 }}>
              <Button onClick={saveProfile} style={{ opacity:saving?0.6:1, pointerEvents:saving?'none':'auto' }}>{saving?'Salvando…':'Salvar alterações'}</Button>
            </div>
          </Card>
        )}

        {tab==='team' && (
          <Card padding={0}>
            <div style={{ padding:'18px 22px', display:'flex', justifyContent:'space-between', alignItems:'center', borderBottom:'1px solid var(--border-subtle)' }}>
              <h3 style={{ margin:0, fontSize:16, fontWeight:700 }}>Equipe</h3>
              <Button icon="plus" size="sm" onClick={()=>window.__toast?.('Convite enviado',{tone:'success'})}>Convidar</Button>
            </div>
            {[
              { n:'Ana Silva',     r:'Owner',     e:'ana@estudionorte.com.br',    s:'Ativo' },
              { n:'Marcos Reis',   r:'Designer',  e:'marcos@estudionorte.com.br', s:'Ativo' },
              { n:'Juliana Pires', r:'Account',   e:'juliana@estudionorte.com.br',s:'Ativo' },
              { n:'Lucas Vieira',  r:'Dev',       e:'lucas@estudionorte.com.br',  s:'Convidado' },
            ].map((m,i) => (
              <div key={m.n} style={{ display:'grid', gridTemplateColumns:'1fr 140px 130px 100px', padding:'14px 22px', borderBottom: i<3?'1px solid var(--border-subtle)':'none', alignItems:'center' }}>
                <span style={{ display:'flex', alignItems:'center', gap:10 }}><Avatar name={m.n} size={32} idx={i}/><div><div style={{ fontSize:13, fontWeight:600 }}>{m.n}</div><div style={{ fontSize:11, color:'var(--fg-muted)' }}>{m.e}</div></div></span>
                <span style={{ fontSize:12 }}>{m.r}</span>
                <Badge tone={m.s==='Ativo'?'success':'warning'}>{m.s}</Badge>
                <Icon d={ICONS.more} size={16} style={{ color:'var(--fg-muted)', cursor:'pointer', justifySelf:'end' }}/>
              </div>
            ))}
          </Card>
        )}

        {tab==='integ' && (
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            <Card padding={18} style={{ borderColor:'rgba(26,115,232,0.3)', background:'rgba(26,115,232,0.04)' }}>
              <div style={{ display:'flex', alignItems:'center', gap:14 }}>
                <div style={{ width:44, height:44, borderRadius:12, background:'linear-gradient(135deg,#4285F4,#34A853)', display:'grid', placeItems:'center', color:'#fff', fontWeight:900, fontSize:22, flexShrink:0 }}>G</div>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:15, fontWeight:700 }}>Google Workspace</div>
                  <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:2 }}>Calendar, Meet e Drive integrados ao inBrivvo</div>
                </div>
                <Button variant="secondary" size="sm" onClick={() => setShowGS(true)}>Configurar</Button>
              </div>
            </Card>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(2,1fr)', gap:14 }}>
              {[
                { n:'Notion',    d:'Importe briefings',              on:false, c:'#7A859A' },
                { n:'Slack',     d:'Notifique a equipe',             on:true,  c:'#7C3AED' },
                { n:'Stripe',    d:'Cobrança automática',            on:false, c:'#1D39C4' },
                { n:'Figma',     d:'Anexe arquivos automaticamente', on:true,  c:'#A0D911' },
                { n:'WhatsApp',  d:'Mensagens com clientes',         on:false, c:'#22C55E' },
              ].map(it => (
                <Card key={it.n} padding={18}>
                  <div style={{ display:'flex', alignItems:'center', gap:12 }}>
                    <span style={{ width:40, height:40, borderRadius:10, background:it.c+'24', display:'grid', placeItems:'center', color:it.c, fontFamily:'var(--font-display)', fontWeight:700, fontSize:14 }}>{it.n[0]}</span>
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:14, fontWeight:700 }}>{it.n}</div>
                      <div style={{ fontSize:11, color:'var(--fg-muted)' }}>{it.d}</div>
                    </div>
                    <span style={{ width:36, height:20, borderRadius:999, background: it.on?'var(--primary)':'var(--bg-elevated)', position:'relative', cursor:'pointer' }}>
                      <span style={{ position:'absolute', top:2, left: it.on?18:2, width:16, height:16, borderRadius:'50%', background:'#fff', transition:'200ms' }}/>
                    </span>
                  </div>
                </Card>
              ))}
            </div>
          </div>
        )}

        {tab==='plano' && (
          <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
            {subStatus === 'active' ? (
              /* ── Assinatura ativa ── */
              <Card padding={24} style={{ background:'linear-gradient(135deg,rgba(34,197,94,0.08),transparent)', borderColor:'rgba(34,197,94,0.3)' }}>
                <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:6 }}>
                  <span style={{ width:10, height:10, borderRadius:'50%', background:'#22C55E', boxShadow:'0 0 0 3px rgba(34,197,94,0.25)', flexShrink:0 }}/>
                  <span style={{ fontSize:13, fontWeight:700, color:'#22C55E', textTransform:'uppercase', letterSpacing:'0.06em' }}>Assinatura ativa</span>
                </div>
                <h3 style={{ margin:'8px 0 4px', fontSize:22, fontWeight:800 }}>
                  Plano Fundadores · {subPeriod === 'annual' ? 'R$397/ano' : 'R$47/mês'}
                </h3>
                <p style={{ color:'var(--fg-secondary)', fontSize:13, marginTop:4, marginBottom:18 }}>
                  {subExpires
                    ? <>Próxima cobrança em <strong>{new Date(subExpires).toLocaleDateString('pt-BR')}</strong>.</>
                    : 'Acesso completo a todas as funcionalidades.'
                  }
                  {' '}Como fundador, você mantém esse preço mesmo quando aumentar.
                </p>
                <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12, marginBottom:18 }}>
                  {[['Projetos','Ilimitados'],['Clientes','Ilimitados'],['Funcionalidades','Todas incluídas']].map(([l,v]) => (
                    <div key={l} style={{ background:'var(--bg-elevated)', padding:'12px 14px', borderRadius:10 }}>
                      <div style={{ fontSize:10, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--fg-muted)' }}>{l}</div>
                      <div style={{ fontSize:16, fontWeight:700, marginTop:4, color:'var(--fg-primary)' }}>{v}</div>
                    </div>
                  ))}
                </div>
                {subPeriod !== 'annual' && (
                  <div style={{ marginBottom:14, padding:'14px 16px', borderRadius:10, background:'linear-gradient(135deg,rgba(250,173,20,0.1),rgba(250,173,20,0.04))', border:'1px solid rgba(250,173,20,0.3)', display:'flex', alignItems:'center', justifyContent:'space-between', gap:12, flexWrap:'wrap' }}>
                    <div>
                      <div style={{ fontSize:13, fontWeight:700, color:'#FAAD14' }}>💰 Economize R$167/ano</div>
                      <div style={{ fontSize:12, color:'var(--fg-secondary)', marginTop:2 }}>Migre para o plano anual — R$397/ano (≈ R$33/mês)</div>
                    </div>
                    <a href={CAKTO_URL_ANUAL} target="_blank" rel="noopener noreferrer"
                      style={{ flexShrink:0, padding:'8px 16px', borderRadius:8, background:'rgba(250,173,20,0.2)', border:'1px solid rgba(250,173,20,0.4)', color:'#FAAD14', fontSize:12, fontWeight:700, textDecoration:'none', whiteSpace:'nowrap' }}>
                      Migrar para anual →
                    </a>
                  </div>
                )}
                <div style={{ display:'flex', gap:10 }}>
                  <Button onClick={() => setModalPlano(true)}>Ver detalhes da assinatura</Button>
                  <Button variant="secondary" onClick={() => setModalFaturas(true)}>Histórico de faturas</Button>
                </div>
              </Card>
            ) : (
              /* ── Sem assinatura ── */
              <Card padding={0} style={{ overflow:'hidden' }}>
                <div style={{ padding:'22px 24px', background:'linear-gradient(135deg,rgba(29,57,196,0.12),transparent)', borderBottom:'1px solid var(--border-subtle)' }}>
                  <div style={{ display:'inline-flex', alignItems:'center', gap:6, padding:'4px 12px', borderRadius:999, background:'rgba(250,173,20,0.15)', border:'1px solid rgba(250,173,20,0.35)', fontSize:11, fontWeight:700, color:'#FAAD14', textTransform:'uppercase', letterSpacing:'0.04em', marginBottom:12 }}>
                    ⭐ Preço de Fundadores
                  </div>
                  <h3 style={{ margin:'0 0 4px', fontSize:22, fontWeight:800 }}>Acesso completo ao inBrivvo</h3>
                  <p style={{ margin:0, color:'var(--fg-secondary)', fontSize:13 }}>
                    Tudo incluído por <strong style={{ color:'var(--geek-blue-200)' }}>R$47/mês</strong> ou <strong style={{ color:'var(--geek-blue-200)' }}>R$397/ano</strong> (-30%).
                    Esse preço é exclusivo para os primeiros assinantes e vai aumentar conforme o produto cresce.
                  </p>
                </div>
                <div style={{ padding:'18px 24px' }}>
                  <div style={{ display:'grid', gridTemplateColumns:'repeat(2,1fr)', gap:'6px 20px', marginBottom:20 }}>
                    {FOUNDERS_FEATURES.map(f => (
                      <div key={f} style={{ display:'flex', alignItems:'center', gap:8, fontSize:12, color:'var(--fg-secondary)' }}>
                        <span style={{ width:14, height:14, borderRadius:'50%', background:'rgba(34,197,94,0.2)', border:'1px solid rgba(34,197,94,0.4)', display:'grid', placeItems:'center', flexShrink:0 }}>
                          <svg width="7" height="7" viewBox="0 0 8 8"><path d="M1 4l2 2 4-4" stroke="#22C55E" strokeWidth="1.5" fill="none" strokeLinecap="round"/></svg>
                        </span>
                        {f}
                      </div>
                    ))}
                  </div>
                  <div style={{ display:'flex', gap:12, flexWrap:'wrap' }}>
                    <a href={CAKTO_URL_MENSAL} target="_blank" rel="noopener noreferrer"
                      style={{ flex:1, minWidth:160, display:'flex', flexDirection:'column', alignItems:'center', padding:'14px 20px', borderRadius:12, border:'1px solid var(--border-strong)', background:'var(--bg-elevated)', textDecoration:'none', cursor:'pointer' }}>
                      <div style={{ fontSize:17, fontWeight:800, color:'var(--fg-primary)' }}>R$47/mês</div>
                      <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:2, marginBottom:10 }}>cancele quando quiser</div>
                      <div style={{ padding:'7px 22px', borderRadius:8, background:'var(--primary)', color:'#fff', fontSize:12, fontWeight:700 }}>Assinar Mensal</div>
                    </a>
                    <a href={CAKTO_URL_ANUAL} target="_blank" rel="noopener noreferrer"
                      style={{ flex:1, minWidth:160, display:'flex', flexDirection:'column', alignItems:'center', padding:'14px 20px', borderRadius:12, border:'2px solid var(--primary)', background:'linear-gradient(135deg,rgba(29,57,196,0.1),transparent)', textDecoration:'none', cursor:'pointer', position:'relative' }}>
                      <div style={{ position:'absolute', top:-1, left:'50%', transform:'translateX(-50%)', background:'var(--primary)', color:'#fff', fontSize:9, fontWeight:800, padding:'3px 12px', borderRadius:'0 0 8px 8px', letterSpacing:'0.06em', textTransform:'uppercase', whiteSpace:'nowrap' }}>MELHOR OFERTA</div>
                      <div style={{ fontSize:17, fontWeight:800, color:'var(--geek-blue-200)', marginTop:8 }}>R$397/ano</div>
                      <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:2, marginBottom:10 }}>≈ R$33/mês · economize R$167</div>
                      <div style={{ padding:'7px 22px', borderRadius:8, background:'var(--primary)', color:'#fff', fontSize:12, fontWeight:700 }}>Assinar Anual</div>
                    </a>
                  </div>
                  <p style={{ margin:'12px 0 0', fontSize:11, color:'var(--fg-muted)', textAlign:'center' }}>
                    Pagamento seguro via Cakto · PIX, cartão de crédito e boleto
                  </p>
                </div>
              </Card>
            )}
          </div>
        )}

        {tab==='notif' && (
          <Card padding={24}>
            <h3 style={{ margin:0, fontSize:18, fontWeight:700 }}>Notificações</h3>
            <div style={{ marginTop:14, display:'flex', flexDirection:'column' }}>
              {[
                ['Comentários em projetos', true],
                ['Novas tarefas atribuídas', true],
                ['Aprovações de orçamento', true],
                ['Pagamentos recebidos', true],
                ['Resumo semanal por e-mail', false],
                ['Lembretes de agenda', true],
              ].map(([l, on], i) => (
                <div key={l} style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'14px 0', borderBottom: i<5?'1px solid var(--border-subtle)':'none' }}>
                  <span style={{ fontSize:13 }}>{l}</span>
                  <span style={{ width:36, height:20, borderRadius:999, background: on?'var(--primary)':'var(--bg-elevated)', position:'relative', cursor:'pointer' }}>
                    <span style={{ position:'absolute', top:2, left: on?18:2, width:16, height:16, borderRadius:'50%', background:'#fff' }}/>
                  </span>
                </div>
              ))}
            </div>
          </Card>
        )}
        {tab==='legal' && (
          window.Legal
            ? React.createElement(window.Legal, null)
            : <Card padding={24}><div style={{ color:'var(--fg-muted)', fontSize:13 }}>Carregando documentos legais…</div></Card>
        )}
      </div>
    </div>

    {modalPlano   && <AssinaturaModal onClose={()=>setModalPlano(false)} subStatus={subStatus} subExpires={subExpires} subPeriod={subPeriod} />}
    {modalFaturas && <HistoricoFaturasModal onClose={()=>setModalFaturas(false)} />}
    {cropModal    && <AvatarCropModal onClose={()=>setCropModal(false)} onSave={handleAvatarSaved} />}
    {showGS && <GoogleIntegrationSettings onClose={() => setShowGS(false)} />}
    </>
  );
}
window.Settings = Settings;
