// Grape Elevate — Integration connect/configure modals.
// Self-contained: a single <IntegrationModal> driven by `state.openIntegration`.

const INTEGRATION_DEFS = {
  Instagram: {
    emoji: '📷',
    color: 'var(--coral)',
    blurb: 'Conecte sua conta business ou criador para que o Grape possa responder DMs, comentários e stories automaticamente.',
    permissions: [
      'Ler e responder Direct Messages',
      'Ler e responder comentários nos seus posts e reels',
      'Receber respostas a stories',
      'Ver lista de seguidores e seguidos',
    ],
    fields: () => ([
      { k: 'handle',   label: 'Conta conectada', readOnly: true, value: '@fabiano.studio' },
      { k: 'account',  label: 'Tipo de conta',  readOnly: true, value: 'Business' },
      { k: 'webhook',  label: 'Webhook URL',    readOnly: true, value: 'https://hooks.grape.app/ig/u_8472a3' },
      { k: 'reply',    label: 'Resposta padrão',
        textarea: true,
        value: 'Oi! Recebi sua mensagem 💜 Vou te responder em instantes.' },
    ]),
  },
  WhatsApp: {
    emoji: '💬',
    color: 'var(--green)',
    blurb: 'Encaminhe leads quentes do Instagram direto para o WhatsApp e responda manualmente ou via fluxo.',
    permissions: [
      'Enviar mensagens via WhatsApp Business API',
      'Receber respostas dos contatos',
      'Sincronizar templates aprovados',
    ],
    fields: () => ([
      { k: 'phone',   label: 'Número conectado', readOnly: true, value: '+55 11 98xxx-xxxx' },
      { k: 'name',    label: 'Nome do remetente', value: 'Grape Studio' },
      { k: 'greeting', label: 'Mensagem de boas-vindas', textarea: true,
        value: 'Oi! Aqui é a equipe Grape, recebemos seu contato pelo Instagram 🍇' },
    ]),
  },
  Mailchimp:    { emoji: '📧', color: 'var(--sun)',   blurb: 'Crie listas no Mailchimp a partir dos leads que o Grape captura.', permissions: ['Criar e atualizar listas', 'Adicionar e remover contatos', 'Disparar campanhas básicas'], fields: () => ([{ k: 'key', label: 'API Key', placeholder: 'us12-xxxxxxxx...' }]) },
  Zapier:       { emoji: '⚡',  color: 'var(--cyan)',  blurb: 'Conecte com 5.000+ apps via Zapier.', permissions: ['Acionar Zaps a partir de eventos do Grape'], fields: () => ([{ k: 'key', label: 'Zapier Webhook URL', value: 'https://hooks.zapier.com/hooks/catch/8123/abcde' }]) },
  'Google Sheets': { emoji: '📊', color: 'var(--grape)', blurb: 'Exporte cada novo lead para uma planilha.', permissions: ['Criar e editar planilhas', 'Adicionar linhas em planilhas existentes'], fields: () => ([{ k: 'sheet', label: 'Planilha de destino', placeholder: 'https://docs.google.com/...' }]) },
  Webhook:      { emoji: '🔗', color: 'var(--text-mute)', blurb: 'POST personalizado para qualquer URL.', permissions: ['Enviar POST com payload JSON em cada evento'], fields: () => ([{ k: 'url', label: 'Endpoint', placeholder: 'https://api.seusite.com/grape' }, { k: 'secret', label: 'Secret (assinatura HMAC)', placeholder: 'sk_...' }]) },
};

function IntegrationModal({ open, integration, status, onClose, onConnect, onDisconnect, onSave }) {
  // Stages: idle → auth (Instagram) | phone → otp (WhatsApp) | key (generic) → success → configure
  // For an already-connected integration, jump straight to "configure".
  const [stage, setStage] = React.useState('idle');
  const [form, setForm] = React.useState({});
  const def = open ? INTEGRATION_DEFS[integration] : null;

  React.useEffect(() => {
    if (!open) return;
    if (status === 'on') {
      // Existing connection — go straight to configure with the saved field values.
      const f = {};
      (def.fields() || []).forEach((x) => { f[x.k] = x.value ?? ''; });
      setForm(f);
      setStage('configure');
    } else {
      setForm({});
      setStage('idle');
    }
  }, [open, integration, status]);

  if (!open || !def) return null;

  const startConnect = () => {
    if (integration === 'Instagram') setStage('auth');
    else if (integration === 'WhatsApp') setStage('phone');
    else setStage('key');
  };
  const finishConnect = () => {
    setStage('success');
    setTimeout(() => {
      onConnect(integration, form);
      // Move into configure view so the user can edit details right after.
      const f = {};
      (def.fields() || []).forEach((x) => { f[x.k] = x.value ?? f[x.k] ?? ''; });
      setForm(f);
      setStage('configure');
    }, 900);
  };

  return (
    <>
      <style>{integStyles}</style>
      <div className="integ-modal-backdrop" onClick={onClose}>
        <div className="integ-modal" onClick={(e) => e.stopPropagation()}>
          <button className="integ-close" onClick={onClose} aria-label="Fechar"><Icons.X size={18} /></button>

          <header className="integ-modal-head">
            <div className="integ-modal-emoji" style={{ background: `color-mix(in oklch, ${def.color} 20%, transparent)` }}>{def.emoji}</div>
            <div>
              <div className="eyebrow">{stage === 'configure' ? 'Configurar' : 'Conectar'}</div>
              <h3 style={{ margin: '2px 0 0', fontSize: 20, fontWeight: 800, letterSpacing: '-0.01em' }}>{integration}</h3>
            </div>
          </header>

          <p className="integ-modal-blurb">{def.blurb}</p>

          {stage === 'idle' && (
            <>
              <div className="integ-perm-card">
                <div className="eyebrow" style={{ marginBottom: 8 }}>O Grape vai precisar</div>
                <ul className="integ-perm-list">
                  {def.permissions.map((p) => (
                    <li key={p}><Icons.Check size={14} /> {p}</li>
                  ))}
                </ul>
              </div>
              <div className="integ-actions">
                <button className="btn" onClick={onClose}>Cancelar</button>
                <button className="btn btn-primary" onClick={startConnect}>
                  Conectar {integration} <Icons.Chevron size={14} />
                </button>
              </div>
            </>
          )}

          {stage === 'auth' && <InstagramAuthStep onCancel={() => setStage('idle')} onAuthorized={() => { setForm({ handle: '@fabiano.studio', account: 'Business', webhook: 'https://hooks.grape.app/ig/u_8472a3', reply: 'Oi! Recebi sua mensagem 💜 Vou te responder em instantes.' }); finishConnect(); }} />}

          {stage === 'phone' && <WhatsappPhoneStep
            onCancel={() => setStage('idle')}
            onSubmit={(phone) => { setForm((f) => ({ ...f, phone })); setStage('otp'); }} />}

          {stage === 'otp' && <WhatsappOtpStep
            phone={form.phone}
            onBack={() => setStage('phone')}
            onSubmit={() => { setForm({ phone: form.phone, name: 'Grape Studio', greeting: 'Oi! Aqui é a equipe Grape, recebemos seu contato pelo Instagram 🍇' }); finishConnect(); }} />}

          {stage === 'key' && (
            <>
              <div className="integ-fields">
                {def.fields().map((f) => (
                  <div className="set-field" key={f.k}>
                    <label>{f.label}</label>
                    <input className="input" type="text" placeholder={f.placeholder || ''}
                           value={form[f.k] || ''} onChange={(e) => setForm({ ...form, [f.k]: e.target.value })} />
                  </div>
                ))}
              </div>
              <div className="integ-actions">
                <button className="btn" onClick={() => setStage('idle')}>Voltar</button>
                <button className="btn btn-primary" onClick={finishConnect}>Conectar</button>
              </div>
            </>
          )}

          {stage === 'success' && (
            <div className="integ-success">
              <div className="integ-success-pulse"><Icons.Check size={36} /></div>
              <h4>Conectado!</h4>
              <p className="muted">Já está pronto pra usar em seus fluxos.</p>
            </div>
          )}

          {stage === 'configure' && (
            <>
              <div className="integ-status-pill"><i /> Conectado · sincronizando há 14 dias</div>
              <div className="integ-fields">
                {def.fields().map((f) => (
                  <div className="set-field" key={f.k}>
                    <label>{f.label} {f.readOnly && <span className="muted" style={{ fontWeight: 400, fontSize: 11 }}>(somente leitura)</span>}</label>
                    {f.textarea ? (
                      <textarea className="input" rows="3" style={{ height: 'auto', padding: 10, fontFamily: 'inherit' }}
                                value={form[f.k] || ''} readOnly={f.readOnly}
                                onChange={(e) => setForm({ ...form, [f.k]: e.target.value })} />
                    ) : (
                      <input className="input" type="text"
                             value={form[f.k] || ''} readOnly={f.readOnly}
                             onChange={(e) => setForm({ ...form, [f.k]: e.target.value })} />
                    )}
                  </div>
                ))}
              </div>
              <div className="integ-actions" style={{ justifyContent: 'space-between' }}>
                <button className="btn" onClick={() => { onDisconnect(integration); onClose(); }}
                        style={{ color: 'var(--coral)', borderColor: 'color-mix(in oklch, var(--coral) 30%, transparent)' }}>
                  <Icons.Trash size={14} /> Desconectar
                </button>
                <div className="row">
                  <button className="btn" onClick={onClose}>Fechar</button>
                  <button className="btn btn-primary" onClick={() => { onSave(integration, form); onClose(); }}>Salvar</button>
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </>
  );
}

// ── Instagram OAuth-style consent step ───────────────────────────────────────
function InstagramAuthStep({ onCancel, onAuthorized }) {
  const [busy, setBusy] = React.useState(false);
  return (
    <div className="integ-oauth">
      <div className="ig-card">
        <div className="ig-card-head">
          <span className="ig-dot" style={{ background: '#FF3B30' }} />
          <span className="ig-dot" style={{ background: '#FFCC00' }} />
          <span className="ig-dot" style={{ background: '#34C759' }} />
          <span style={{ flex: 1, textAlign: 'center', fontSize: 11, color: 'var(--text-mute)' }}>instagram.com/oauth/authorize</span>
        </div>
        <div className="ig-card-body">
          <div className="ig-logo">📷</div>
          <h4 style={{ margin: 0 }}>Autorizar <b>Grape Elevate</b></h4>
          <p className="muted" style={{ fontSize: 13, margin: '4px 0 12px', textAlign: 'center' }}>Você está conectando como <b>@fabiano.studio</b></p>
          <ul className="ig-perms">
            <li><Icons.Check size={13} /> Ler e enviar mensagens diretas</li>
            <li><Icons.Check size={13} /> Responder comentários</li>
            <li><Icons.Check size={13} /> Receber respostas a stories</li>
          </ul>
          <div className="row" style={{ gap: 8, marginTop: 14, justifyContent: 'flex-end', width: '100%' }}>
            <button className="btn btn-sm" onClick={onCancel}>Cancelar</button>
            <button className="btn btn-primary btn-sm" disabled={busy}
                    onClick={() => { setBusy(true); setTimeout(onAuthorized, 700); }}>
              {busy ? 'Conectando…' : 'Autorizar'}
            </button>
          </div>
        </div>
      </div>
      <p className="muted" style={{ fontSize: 12, marginTop: 8, textAlign: 'center' }}>Simulação do consentimento OAuth do Instagram.</p>
    </div>
  );
}

// ── WhatsApp phone-number step ───────────────────────────────────────────────
function WhatsappPhoneStep({ onCancel, onSubmit }) {
  const [ddi, setDdi] = React.useState('+55');
  const [num, setNum] = React.useState('');
  const valid = num.replace(/\D/g, '').length >= 8;
  const format = (s) => {
    const d = s.replace(/\D/g, '').slice(0, 11);
    if (d.length <= 2) return d;
    if (d.length <= 7) return `(${d.slice(0,2)}) ${d.slice(2)}`;
    return `(${d.slice(0,2)}) ${d.slice(2,7)}-${d.slice(7)}`;
  };
  return (
    <>
      <div className="set-field">
        <label>Seu número do WhatsApp Business</label>
        <div className="row" style={{ gap: 8 }}>
          <input className="input" style={{ width: 80, textAlign: 'center' }} value={ddi} onChange={(e) => setDdi(e.target.value)} />
          <input className="input" style={{ flex: 1 }} placeholder="(11) 98765-4321" value={num} onChange={(e) => setNum(format(e.target.value))} />
        </div>
        <p className="muted" style={{ fontSize: 12, margin: '4px 0 0' }}>Vamos enviar um código de 6 dígitos por SMS pra confirmar.</p>
      </div>
      <div className="integ-actions">
        <button className="btn" onClick={onCancel}>Voltar</button>
        <button className="btn btn-primary" disabled={!valid} onClick={() => onSubmit(`${ddi} ${num}`)}>Enviar código</button>
      </div>
    </>
  );
}

// ── WhatsApp OTP step ────────────────────────────────────────────────────────
function WhatsappOtpStep({ phone, onBack, onSubmit }) {
  const [digits, setDigits] = React.useState(['', '', '', '', '', '']);
  const refs = React.useRef([]);
  const onInput = (i, v) => {
    const ch = v.replace(/\D/g, '').slice(0, 1);
    const next = [...digits];
    next[i] = ch;
    setDigits(next);
    if (ch && i < 5) refs.current[i + 1]?.focus();
  };
  const onKey = (i, e) => {
    if (e.key === 'Backspace' && !digits[i] && i > 0) refs.current[i - 1]?.focus();
  };
  const filled = digits.every((d) => d);
  return (
    <>
      <p className="muted" style={{ fontSize: 13, marginTop: 0 }}>Enviamos um código para <b>{phone}</b>. Para a demo, qualquer 6 dígitos funcionam.</p>
      <div className="otp-row">
        {digits.map((d, i) => (
          <input key={i} className="otp-input" inputMode="numeric" maxLength="1"
                 ref={(el) => (refs.current[i] = el)}
                 value={d}
                 onChange={(e) => onInput(i, e.target.value)}
                 onKeyDown={(e) => onKey(i, e)} />
        ))}
      </div>
      <button className="btn-ghost btn btn-sm" style={{ alignSelf: 'flex-start' }} onClick={() => setDigits(['1','2','3','4','5','6'])}>
        ✨ Auto-preencher (demo)
      </button>
      <div className="integ-actions">
        <button className="btn" onClick={onBack}>Voltar</button>
        <button className="btn btn-primary" disabled={!filled} onClick={onSubmit}>Confirmar</button>
      </div>
    </>
  );
}

const integStyles = `
.integ-modal-backdrop {
  position: fixed; inset: 0;
  background: color-mix(in oklch, var(--bg) 70%, #000);
  backdrop-filter: blur(8px);
  display: flex; align-items: center; justify-content: center;
  padding: 24px; z-index: 1500;
  animation: fade-in 180ms ease;
}
@keyframes fade-in { from { opacity: 0; } }
.integ-modal {
  width: min(560px, 100%);
  max-height: 92vh; overflow-y: auto;
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-pop);
  padding: 26px;
  display: flex; flex-direction: column; gap: 14px;
  position: relative;
  animation: pop-in 220ms cubic-bezier(.2,.9,.3,1.1);
}
@keyframes pop-in { from { opacity: 0; transform: translateY(12px) scale(0.97); } }
.integ-close {
  position: absolute; top: 14px; right: 14px;
  background: transparent; border: 0; cursor: pointer;
  width: 32px; height: 32px; border-radius: 8px;
  display: flex; align-items: center; justify-content: center;
  color: var(--text-mute);
}
.integ-close:hover { background: var(--surface-2); color: var(--text); }

.integ-modal-head { display: flex; align-items: center; gap: 14px; }
.integ-modal-emoji {
  width: 54px; height: 54px; border-radius: 14px;
  display: flex; align-items: center; justify-content: center;
  font-size: 28px;
}
.integ-modal-blurb { margin: 0; color: var(--text-soft); font-size: 14px; line-height: 1.5; }

.integ-perm-card {
  padding: 14px 16px; border-radius: 12px;
  background: var(--surface-2); border: 1px solid var(--line);
}
.integ-perm-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; font-size: 13.5px; color: var(--text-soft); }
.integ-perm-list li { display: flex; align-items: center; gap: 8px; }
.integ-perm-list svg { color: var(--green); flex-shrink: 0; }

.integ-actions { display: flex; gap: 8px; justify-content: flex-end; padding-top: 6px; }

.integ-fields { display: flex; flex-direction: column; gap: 12px; }

.integ-status-pill {
  display: inline-flex; align-items: center; gap: 8px;
  align-self: flex-start;
  padding: 5px 12px;
  border-radius: 999px;
  background: color-mix(in oklch, var(--green) 14%, var(--surface));
  color: var(--green); border: 1px solid color-mix(in oklch, var(--green) 26%, transparent);
  font-weight: 600; font-size: 12px;
}
.integ-status-pill i { width: 7px; height: 7px; border-radius: 50%; background: var(--green); box-shadow: 0 0 0 3px color-mix(in oklch, var(--green) 30%, transparent); }

.integ-success { display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 30px 10px 10px; }
.integ-success h4 { margin: 0; font-size: 18px; }
.integ-success-pulse {
  width: 78px; height: 78px; border-radius: 50%;
  background: color-mix(in oklch, var(--green) 22%, transparent);
  display: flex; align-items: center; justify-content: center;
  color: var(--green);
  animation: pulse 1.6s ease-in-out infinite;
}
@keyframes pulse { 50% { box-shadow: 0 0 0 14px color-mix(in oklch, var(--green) 0%, transparent); } 0%, 100% { box-shadow: 0 0 0 0 color-mix(in oklch, var(--green) 30%, transparent); } }

.ig-card {
  border-radius: 14px; overflow: hidden;
  border: 1px solid var(--line);
  background: var(--surface-2);
  width: 100%;
}
.ig-card-head {
  display: flex; align-items: center; gap: 6px;
  padding: 8px 12px;
  background: var(--surface-3);
  border-bottom: 1px solid var(--line);
}
.ig-dot { width: 10px; height: 10px; border-radius: 50%; }
.ig-card-body { padding: 22px; display: flex; flex-direction: column; align-items: center; }
.ig-logo {
  width: 60px; height: 60px; border-radius: 14px;
  background: linear-gradient(135deg, #F58529 0%, #DD2A7B 50%, #8134AF 100%);
  display: flex; align-items: center; justify-content: center;
  font-size: 30px;
  margin-bottom: 12px;
}
.ig-perms { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 5px; font-size: 12.5px; color: var(--text-soft); align-self: stretch; padding: 10px 0; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
.ig-perms li { display: flex; align-items: center; gap: 8px; }
.ig-perms svg { color: var(--green); flex-shrink: 0; }

.otp-row { display: flex; gap: 8px; margin: 8px 0; }
.otp-input {
  width: 48px; height: 56px;
  text-align: center;
  font-size: 22px; font-weight: 700;
  font-family: var(--font-mono);
  border: 1.5px solid var(--line);
  border-radius: 10px;
  background: var(--surface);
  color: var(--text);
  outline: none;
  transition: border-color 120ms, box-shadow 120ms;
}
.otp-input:focus { border-color: var(--grape); box-shadow: 0 0 0 3px color-mix(in oklch, var(--grape) 22%, transparent); }
`;

window.IntegrationModal = IntegrationModal;
window.INTEGRATION_DEFS = INTEGRATION_DEFS;
