// Grape Elevate — Settings screen

function Settings({ t, lang }) {
  const [section, setSection] = React.useState('account');
  const [notif, setNotif] = React.useState({ dm: true, weekly: true, team: false });
  const [acct, setAcct] = React.useState({ name: 'Fabiano Studio', email: 'fabiano@grape.app', handle: '@fabiano.studio' });
  const [saved, setSaved] = React.useState(false);
  const [integrations, setIntegrations] = React.useState({
    Instagram: 'on', WhatsApp: 'off', Mailchimp: 'off', Zapier: 'on', 'Google Sheets': 'off', Webhook: 'off',
  });
  const [integOpen, setIntegOpen] = React.useState(null); // name of integration or null
  const [toast, setToast] = React.useState(null);
  const showToast = (m) => { setToast(m); setTimeout(() => setToast(null), 1800); };

  const sections = [
    { k: 'account',  label: t('set.account'),  icon: <Icons.Users size={16} /> },
    { k: 'notif',    label: t('set.notif'),    icon: <Icons.Bell size={16} /> },
    { k: 'integ',    label: t('set.integ'),    icon: <Icons.Link size={16} /> },
    { k: 'billing',  label: t('set.billing'),  icon: <Icons.Card size={16} /> },
    { k: 'team',     label: t('set.team'),     icon: <Icons.Users size={16} /> },
    { k: 'danger',   label: t('set.danger'),   icon: <Icons.Trash size={16} /> },
  ];

  const save = () => { setSaved(true); setTimeout(() => setSaved(false), 1600); };

  return (
    <>
      <style>{setStyles}</style>
      <div className="page-head">
        <div>
          <h1 className="page-title">{t('set.title')}</h1>
          <p className="page-sub">{t('set.subtitle')}</p>
        </div>
      </div>

      <div className="set-shell">
        <aside className="set-nav">
          {sections.map((s) => (
            <button key={s.k} className={`set-nav-item ${section === s.k ? 'active' : ''} ${s.k === 'danger' ? 'danger' : ''}`}
                    onClick={() => setSection(s.k)}>
              {s.icon} {s.label}
            </button>
          ))}
        </aside>
        <section className="set-body">
          {section === 'account' && (
            <div className="set-card">
              <h3>{t('set.account')}</h3>
              <div className="set-field"><label>{t('set.field.name')}</label>
                <input className="input" value={acct.name} onChange={(e) => setAcct({ ...acct, name: e.target.value })} /></div>
              <div className="set-field"><label>{t('set.field.email')}</label>
                <input className="input" type="email" value={acct.email} onChange={(e) => setAcct({ ...acct, email: e.target.value })} /></div>
              <div className="set-field"><label>{t('set.field.handle')}</label>
                <div className="row" style={{ gap: 8 }}>
                  <input className="input" value={acct.handle} onChange={(e) => setAcct({ ...acct, handle: e.target.value })} style={{ flex: 1 }} />
                  <span className="pill pill-live"><i className="dot" style={{ width: 6, height: 6, borderRadius: '50%', background: 'currentColor' }} /> conectada</span>
                </div>
              </div>
              <button className="btn btn-primary" onClick={save}>{t('set.save')}</button>
              {saved && <div className="toast">✓ Alterações salvas</div>}
            </div>
          )}

          {section === 'notif' && (
            <div className="set-card">
              <h3>{t('set.notif')}</h3>
              {[
                { k: 'dm',     l: t('set.notif.dm'),     d: t('set.notif.dmDesc') },
                { k: 'weekly', l: t('set.notif.weekly'), d: t('set.notif.weeklyDesc') },
                { k: 'team',   l: t('set.notif.team'),   d: t('set.notif.teamDesc') },
              ].map((row) => (
                <div className="set-toggle-row" key={row.k}>
                  <div>
                    <div style={{ fontWeight: 600 }}>{row.l}</div>
                    <div className="muted" style={{ fontSize: 12.5 }}>{row.d}</div>
                  </div>
                  <button className="switch" data-on={notif[row.k] ? '1' : '0'} onClick={() => setNotif({ ...notif, [row.k]: !notif[row.k] })}><i /></button>
                </div>
              ))}
            </div>
          )}

          {section === 'integ' && (
            <div className="set-card">
              <h3>{t('set.integ')}</h3>
              <div className="integ-grid">
                {[
                  { name: 'Instagram', desc: integrations.Instagram === 'on' ? 'Conta principal conectada' : 'Responda DMs, comentários e stories', emoji: '📷', color: 'var(--coral)' },
                  { name: 'WhatsApp', desc: 'Encaminhe leads quentes pro WhatsApp', emoji: '💬', color: 'var(--green)' },
                  { name: 'Mailchimp', desc: 'Crie listas a partir de leads', emoji: '📧', color: 'var(--sun)' },
                  { name: 'Zapier',    desc: '5000+ apps via Zapier', emoji: '⚡', color: 'var(--cyan)' },
                  { name: 'Google Sheets', desc: 'Exporte leads automaticamente', emoji: '📊', color: 'var(--grape)' },
                  { name: 'Webhook',   desc: 'POST personalizado pra qualquer URL', emoji: '🔗', color: 'var(--text-mute)' },
                ].map((it) => {
                  const on = integrations[it.name] === 'on';
                  return (
                    <div key={it.name} className="integ-card">
                      <div className="integ-emoji" style={{ background: `color-mix(in oklch, ${it.color} 18%, transparent)` }}>{it.emoji}</div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div className="row-between">
                          <b>{it.name}</b>
                          {on && <span className="pill pill-live"><i className="dot" style={{ width: 5, height: 5, borderRadius: '50%', background: 'currentColor' }} /> on</span>}
                        </div>
                        <div className="muted" style={{ fontSize: 12 }}>{it.desc}</div>
                      </div>
                      <button className={on ? 'btn btn-sm' : 'btn btn-primary btn-sm'} onClick={() => setIntegOpen(it.name)}>
                        {on ? 'Configurar' : 'Conectar'}
                      </button>
                    </div>
                  );
                })}
              </div>
              <IntegrationModal
                open={!!integOpen}
                integration={integOpen}
                status={integOpen ? integrations[integOpen] : 'off'}
                onClose={() => setIntegOpen(null)}
                onConnect={(name) => { setIntegrations((m) => ({ ...m, [name]: 'on' })); showToast(`${name} conectado 🎉`); }}
                onDisconnect={(name) => { setIntegrations((m) => ({ ...m, [name]: 'off' })); showToast(`${name} desconectado`); }}
                onSave={(name) => showToast(`${name}: configurações salvas`)}
              />
              {toast && <div className="toast">{toast}</div>}
            </div>
          )}

          {section === 'billing' && (
            <div className="set-card">
              <h3>{t('set.billing')}</h3>
              <div className="plan-current">
                <div>
                  <div className="eyebrow">{t('set.plan.current')}</div>
                  <div className="plan-name gradient-text">Grape Free</div>
                  <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>1.000 contatos · automações ilimitadas · 1 conta</div>
                </div>
                <div className="plan-price">
                  <b>R$ 0</b><span className="muted">/mês</span>
                </div>
              </div>
              <div className="plan-grid">
                {[
                  { name: 'Starter', price: '29', desc: '5.000 contatos', feats: ['Inbox unificada', '1 conta Instagram', 'Suporte por e-mail'] },
                  { name: 'Pro', price: '79', desc: '25.000 contatos', popular: true, feats: ['Tudo do Starter', 'IA assistente', 'Equipe (3 lugares)', 'Webhooks'] },
                  { name: 'Business', price: '199', desc: 'Contatos ilimitados', feats: ['Tudo do Pro', 'Suporte prioritário', 'White-label', 'SLA 99.9%'] },
                ].map((p) => (
                  <div key={p.name} className={`plan-card ${p.popular ? 'popular' : ''}`}>
                    {p.popular && <span className="pill pill-pop">★ Recomendado</span>}
                    <h4>{p.name}</h4>
                    <div className="plan-amount"><span className="plan-currency">R$</span><b>{p.price}</b><span className="muted">/mês</span></div>
                    <div className="muted" style={{ fontSize: 13, marginBottom: 10 }}>{p.desc}</div>
                    <ul className="plan-feats">
                      {p.feats.map((f) => <li key={f}><Icons.Check size={14} /> {f}</li>)}
                    </ul>
                    <button className={`btn ${p.popular ? 'btn-primary' : ''}`}>{p.popular ? 'Mudar para Pro' : 'Selecionar'}</button>
                  </div>
                ))}
              </div>
              <p className="muted" style={{ fontSize: 12.5, marginTop: 4 }}>Todos os planos com 14 dias grátis. Cancele quando quiser.</p>
            </div>
          )}

          {section === 'team' && (
            <div className="set-card">
              <h3>{t('set.team')}</h3>
              <p className="muted" style={{ fontSize: 13, marginTop: -8 }}>Convide colegas para responder DMs e editar fluxos.</p>
              <div className="team-list">
                {[
                  { n: 'Fabiano', e: 'fabiano@grape.app', role: 'Owner', hue: 285 },
                  { n: 'Bruna Tavares', e: 'bruna@grape.app', role: 'Editor', hue: 30 },
                  { n: 'Caio Mendes', e: 'caio@grape.app', role: 'Atendimento', hue: 200 },
                ].map((m) => (
                  <div key={m.e} className="team-row">
                    <Avatar hue={m.hue} name={m.n} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 600 }}>{m.n}</div>
                      <div className="muted" style={{ fontSize: 12 }}>{m.e}</div>
                    </div>
                    <span className="pill">{m.role}</span>
                    <button className="btn btn-ghost btn-icon"><Icons.Dots size={16} /></button>
                  </div>
                ))}
              </div>
              <button className="btn"><Icons.Plus size={14} /> Convidar pessoa</button>
            </div>
          )}

          {section === 'danger' && (
            <div className="set-card danger-card">
              <h3 style={{ color: 'var(--coral)' }}>{t('set.danger')}</h3>
              <div className="danger-row">
                <div>
                  <b>{t('set.delete')}</b>
                  <div className="muted" style={{ fontSize: 13 }}>Apaga todas as automações, conversas e dados. Não pode ser desfeito.</div>
                </div>
                <button className="btn" style={{ color: 'var(--coral)', borderColor: 'color-mix(in oklch, var(--coral) 30%, transparent)' }}>
                  <Icons.Trash size={14} /> Excluir
                </button>
              </div>
            </div>
          )}
        </section>
      </div>
    </>
  );
}

const setStyles = `
.set-shell { display: grid; grid-template-columns: 220px 1fr; gap: 18px; }
@media (max-width: 900px) { .set-shell { grid-template-columns: 1fr; } }
.set-nav { display: flex; flex-direction: column; gap: 2px; padding: 8px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface); box-shadow: var(--shadow-card); height: fit-content; position: sticky; top: 24px; }
.set-nav-item { display: flex; align-items: center; gap: 10px; padding: 9px 12px; border-radius: 8px; background: transparent; border: 0; color: var(--text-soft); font-weight: 500; font-size: 13px; cursor: pointer; text-align: left; transition: background 120ms, color 120ms; }
.set-nav-item:hover { background: var(--surface-2); color: var(--text); }
.set-nav-item.active { background: color-mix(in oklch, var(--grape) 14%, var(--surface)); color: var(--text); box-shadow: inset 0 0 0 1px color-mix(in oklch, var(--grape) 25%, transparent); }
.set-nav-item.danger { color: color-mix(in oklch, var(--coral) 80%, var(--text-soft)); margin-top: auto; }

.set-card { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 24px; box-shadow: var(--shadow-card); display: flex; flex-direction: column; gap: 14px; }
.set-card h3 { margin: 0 0 6px; font-size: 18px; letter-spacing: -0.01em; font-weight: 700; }
.set-card .btn-primary { align-self: flex-start; }
.set-field { display: flex; flex-direction: column; gap: 6px; max-width: 480px; }
.set-field label { font-size: 12.5px; font-weight: 600; color: var(--text-soft); }
.set-field .input { font-family: inherit; }
.set-toggle-row { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 14px 0; border-top: 1px solid var(--line); }
.set-toggle-row:first-of-type { border-top: 0; padding-top: 0; }

.integ-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
@media (max-width: 800px) { .integ-grid { grid-template-columns: 1fr; } }
.integ-card { display: flex; align-items: center; gap: 12px; padding: 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface-2); }
.integ-emoji { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px; }

.plan-current { display: flex; justify-content: space-between; align-items: flex-end; padding: 18px; border-radius: var(--radius); background: linear-gradient(135deg, color-mix(in oklch, var(--grape) 12%, var(--surface-2)) 0%, color-mix(in oklch, var(--cyan) 10%, var(--surface-2)) 100%); border: 1px solid var(--line); }
.plan-name { font-size: 24px; font-weight: 800; letter-spacing: -0.02em; }
.plan-price b { font-size: 24px; font-weight: 800; }
.plan-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
@media (max-width: 900px) { .plan-grid { grid-template-columns: 1fr; } }
.plan-card { padding: 18px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface); display: flex; flex-direction: column; gap: 8px; position: relative; }
.plan-card.popular { border-color: var(--grape); box-shadow: 0 0 0 4px color-mix(in oklch, var(--grape) 16%, transparent); }
.plan-card h4 { margin: 0; font-size: 17px; font-weight: 700; }
.plan-amount { display: flex; align-items: baseline; gap: 2px; }
.plan-amount b { font-size: 32px; font-weight: 800; letter-spacing: -0.02em; }
.plan-currency { font-size: 13px; color: var(--text-mute); }
.plan-feats { list-style: none; padding: 0; margin: 6px 0; display: flex; flex-direction: column; gap: 6px; font-size: 13px; color: var(--text-soft); }
.plan-feats li { display: flex; align-items: center; gap: 8px; }
.plan-feats svg { color: var(--green); flex-shrink: 0; }
.plan-card > .btn { margin-top: auto; }
.plan-card .pill-pop { position: absolute; top: -10px; right: 14px; }

.team-list { display: flex; flex-direction: column; gap: 6px; }
.team-row { display: flex; align-items: center; gap: 12px; padding: 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface-2); }

.danger-card { border-color: color-mix(in oklch, var(--coral) 30%, var(--line)); }
.danger-row { display: flex; justify-content: space-between; align-items: center; padding: 14px; border: 1px dashed color-mix(in oklch, var(--coral) 35%, transparent); border-radius: 12px; background: color-mix(in oklch, var(--coral) 6%, transparent); gap: 12px; }
`;

window.Settings = Settings;
