// Grape Elevate — Roadmap / Technical plan screen
// Comprehensive deliverable for handing off to a developer: architecture,
// stack, costs, Meta setup checklist, code skeletons, and timeline.

function Roadmap({ t }) {
  return (
    <>
      <style>{roadmapStyles}</style>
      <div className="page-head">
        <div>
          <h1 className="page-title">Plano técnico <span className="gradient-text">para tirar do papel</span></h1>
          <p className="page-sub">Tudo que falta entre esse protótipo e um produto que roda de verdade no Instagram + WhatsApp. Pode mandar pra um dev ou estudar pra fazer você mesmo.</p>
        </div>
        <div className="row">
          <button className="btn" onClick={() => window.print()}><Icons.Copy size={14} /> Imprimir</button>
        </div>
      </div>

      <section className="rm-hero">
        <div>
          <div className="eyebrow">Resumo</div>
          <h2>MVP em ~4 semanas, custo inicial &lt; R$ 100/mês</h2>
          <p>O protótipo já cobre 100% da UX. O que falta é o <b>backend</b> que conversa com a API do Instagram, um <b>banco de dados</b> pra guardar contatos e fluxos, e a <b>aprovação do app na Meta</b> (passo mais demorado, mas é trabalho de espera, não de código).</p>
        </div>
        <Architecture />
      </section>

      <section className="rm-grid">
        <div className="rm-card">
          <div className="rm-card-head"><span className="rm-emoji">🛠️</span><h3>Stack recomendada</h3></div>
          <table className="rm-table">
            <tbody>
              <tr><th>Frontend</th><td><b>Este protótipo</b> (React + HTML) — só trocar dados mockados por <code>fetch('/api/...')</code></td></tr>
              <tr><th>Backend</th><td><b>Node.js (Fastify)</b> ou <b>Python (FastAPI)</b> — leve e rápido pra webhooks</td></tr>
              <tr><th>Banco</th><td><b>Postgres no Supabase</b> ou <b>Neon</b> — grátis até 500MB</td></tr>
              <tr><th>Hospedagem</th><td><b>Railway</b>, <b>Fly.io</b> ou <b>Render</b> — R$ 0 a R$ 50/mês</td></tr>
              <tr><th>Fila</th><td><b>BullMQ + Redis</b> (Upstash grátis) — pra atrasos e retentativas</td></tr>
              <tr><th>Auth</th><td><b>Supabase Auth</b> ou <b>Clerk</b> — pronto, com login social</td></tr>
              <tr><th>Pagamento</th><td><b>Stripe</b> (cartão internacional) ou <b>Pagar.me</b> (PIX/boleto)</td></tr>
            </tbody>
          </table>
        </div>

        <div className="rm-card">
          <div className="rm-card-head"><span className="rm-emoji">💸</span><h3>Custos estimados</h3></div>
          <div className="rm-cost-tier">
            <div className="rm-cost-name">Fase 1 — Validação (você sozinho)</div>
            <div className="rm-cost-amount">R$ 0–80<span className="muted">/mês</span></div>
            <ul>
              <li>Hospedagem free tier (Railway/Fly)</li>
              <li>Supabase free</li>
              <li>Domínio: ~R$ 40/ano</li>
              <li>WhatsApp Cloud API: 1.000 conversas grátis/mês</li>
            </ul>
          </div>
          <div className="rm-cost-tier">
            <div className="rm-cost-name">Fase 2 — Primeiros 100 clientes</div>
            <div className="rm-cost-amount">R$ 300–800<span className="muted">/mês</span></div>
            <ul>
              <li>Hospedagem paga ($20–50/mês)</li>
              <li>Postgres médio</li>
              <li>Custo variável de WhatsApp por mensagem</li>
            </ul>
          </div>
          <div className="rm-cost-tier">
            <div className="rm-cost-name">⚠️ Variável: WhatsApp</div>
            <div className="rm-cost-amount">~R$ 0,03–0,30<span className="muted">/conversa</span></div>
            <ul>
              <li>"Conversa" = 24h de troca de mensagens com 1 número</li>
              <li>Mensagem iniciada pelo usuário (resposta) costuma ser grátis</li>
            </ul>
          </div>
        </div>
      </section>

      <section className="rm-card">
        <div className="rm-card-head"><span className="rm-emoji">📋</span><h3>Checklist Meta — o caminho oficial</h3></div>
        <p className="muted" style={{ marginTop: 0 }}>Tudo aqui é grátis, mas leva tempo. Comece já em paralelo ao desenvolvimento.</p>
        <ol className="rm-steps">
          <li><b>Crie uma conta Meta Business</b> em <a href="https://business.facebook.com" target="_blank" rel="noopener">business.facebook.com</a>. Use CNPJ se possível.</li>
          <li><b>Verifique a empresa</b> (Configurações → Centro de segurança) — exige documento da empresa.</li>
          <li><b>Vincule a página do Facebook</b> que vai representar o app.</li>
          <li><b>Conecte sua conta do Instagram</b> como <i>Business</i> (perfis pessoais não funcionam).</li>
          <li><b>Registre o app</b> em <a href="https://developers.facebook.com" target="_blank" rel="noopener">developers.facebook.com</a> → Meus Apps → Criar app → tipo "Business".</li>
          <li><b>Adicione os produtos</b>: <code>Instagram Graph API</code>, <code>WhatsApp Business Platform</code>, <code>Webhooks</code>.</li>
          <li><b>Configure URL de webhook</b> apontando pro seu backend (precisa ser HTTPS).</li>
          <li><b>Solicite as permissões</b>: <code>instagram_basic</code>, <code>instagram_manage_messages</code>, <code>instagram_manage_comments</code>, <code>pages_show_list</code>, <code>pages_messaging</code>. <span className="rm-warn">⏱️ Revisão demora 3–14 dias</span></li>
          <li><b>Grave um vídeo</b> (~3 min) demonstrando o app pra revisão — exigência da Meta.</li>
          <li><b>Saia do "modo desenvolvimento"</b> — quando aprovado, o app vai ao ar pra qualquer usuário.</li>
        </ol>
      </section>

      <section className="rm-card">
        <div className="rm-card-head"><span className="rm-emoji">🧱</span><h3>Esqueleto do backend</h3></div>
        <p className="muted" style={{ marginTop: 0 }}>Node + Fastify. Cole isso num repositório novo pra começar.</p>
        <CodeBlock title="package.json (deps essenciais)">{`{
  "dependencies": {
    "fastify": "^4",
    "@supabase/supabase-js": "^2",
    "axios": "^1",
    "bullmq": "^5",
    "dotenv": "^16",
    "zod": "^3"
  }
}`}</CodeBlock>
        <CodeBlock title="server.js — webhook do Instagram (recebe comentários e DMs)">{`import Fastify from 'fastify';
import { runAutomation } from './engine.js';

const app = Fastify();
const VERIFY_TOKEN = process.env.META_VERIFY_TOKEN;

// 1. Verificação inicial do webhook (Meta envia GET pra confirmar URL)
app.get('/webhook/instagram', async (req, reply) => {
  const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;
  if (mode === 'subscribe' && token === VERIFY_TOKEN) return reply.send(challenge);
  return reply.code(403).send();
});

// 2. Eventos: comentários, mensagens, story replies...
app.post('/webhook/instagram', async (req, reply) => {
  const { entry } = req.body;
  for (const e of entry) {
    for (const change of e.changes || []) {
      // Ex: novo comentário em um post
      if (change.field === 'comments') {
        const { id, text, from } = change.value;
        await runAutomation({ type: 'comment', text, sender: from, commentId: id });
      }
    }
    for (const msg of e.messaging || []) {
      // Ex: DM recebida
      await runAutomation({ type: 'dm', text: msg.message.text, sender: msg.sender });
    }
  }
  return reply.send('OK');
});

app.listen({ port: process.env.PORT || 3000, host: '0.0.0.0' });`}</CodeBlock>
        <CodeBlock title="engine.js — executor de fluxos (resumido)">{`import axios from 'axios';
import { supabase } from './db.js';

// Casa um evento com automações ativas e roda os passos do fluxo.
export async function runAutomation(event) {
  const { data: autos } = await supabase
    .from('automations')
    .select('*')
    .eq('status', 'live')
    .eq('trigger_type', event.type);

  for (const auto of autos || []) {
    // Filtro por palavra-chave (case-insensitive)
    if (auto.trigger_keyword && !event.text?.toLowerCase().includes(auto.trigger_keyword.toLowerCase())) continue;

    for (const step of auto.flow) {
      if (step.type === 'wait') await sleep(step.config.mins * 60_000);
      if (step.type === 'sendDm') await sendDm(event.sender.id, step.config.text);
      if (step.type === 'sendLink') await sendDm(event.sender.id, step.config.cta + ' ' + step.config.url);
      if (step.type === 'tag') await tagContact(event.sender.id, step.config.tag);
    }

    // Conta execução pro analytics
    await supabase.rpc('increment_runs', { auto_id: auto.id });
  }
}

async function sendDm(userId, text) {
  await axios.post(\`https://graph.facebook.com/v18.0/me/messages\`, {
    recipient: { id: userId },
    message: { text },
  }, { params: { access_token: process.env.IG_ACCESS_TOKEN } });
}`}</CodeBlock>
      </section>

      <section className="rm-card">
        <div className="rm-card-head"><span className="rm-emoji">🗓️</span><h3>Roadmap de 4 semanas (MVP)</h3></div>
        <Timeline />
      </section>

      <section className="rm-card rm-cta">
        <div>
          <h3 style={{ margin: 0 }}>Quer ajuda pra encontrar um dev?</h3>
          <p className="muted" style={{ margin: '4px 0 0' }}>Um freelancer Node + React experiente vai cobrar entre R$ 8k–25k pra implementar o MVP em ~1 mês. Plataformas: Workana, GetNinjas, ou peça indicação em grupos de devs no Telegram.</p>
        </div>
      </section>
    </>
  );
}

// ── Architecture diagram (inline SVG) ────────────────────────────────────────
function Architecture() {
  return (
    <svg viewBox="0 0 520 280" className="rm-arch" width="100%" preserveAspectRatio="xMidYMid meet">
      <defs>
        <marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto">
          <path d="M0 0 L10 5 L0 10 z" fill="var(--text-mute)" />
        </marker>
      </defs>
      {/* Instagram + WhatsApp */}
      <g transform="translate(20,30)">
        <rect width="120" height="64" rx="14" fill="url(#ig-grad)" />
        <defs>
          <linearGradient id="ig-grad" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#F58529" /><stop offset="100%" stopColor="#8134AF" />
          </linearGradient>
        </defs>
        <text x="60" y="28" textAnchor="middle" fill="#fff" fontSize="13" fontWeight="700">Instagram</text>
        <text x="60" y="46" textAnchor="middle" fill="#fff" opacity=".75" fontSize="10.5">Graph API + Webhooks</text>
      </g>
      <g transform="translate(20,108)">
        <rect width="120" height="64" rx="14" fill="#25D366" />
        <text x="60" y="28" textAnchor="middle" fill="#fff" fontSize="13" fontWeight="700">WhatsApp</text>
        <text x="60" y="46" textAnchor="middle" fill="#fff" opacity=".75" fontSize="10.5">Cloud API</text>
      </g>
      <g transform="translate(20,186)">
        <rect width="120" height="64" rx="14" fill="#1877F2" />
        <text x="60" y="28" textAnchor="middle" fill="#fff" fontSize="13" fontWeight="700">Stripe</text>
        <text x="60" y="46" textAnchor="middle" fill="#fff" opacity=".75" fontSize="10.5">Cobrança</text>
      </g>
      {/* Backend */}
      <g transform="translate(200,80)">
        <rect width="160" height="120" rx="14" fill="var(--surface)" stroke="var(--grape)" strokeWidth="2" />
        <text x="80" y="26" textAnchor="middle" fill="var(--text)" fontSize="13" fontWeight="800">Backend Grape</text>
        <text x="80" y="46" textAnchor="middle" fill="var(--text-soft)" fontSize="11">Node + Fastify</text>
        <rect x="14" y="58" width="64" height="22" rx="6" fill="var(--surface-2)" />
        <text x="46" y="73" textAnchor="middle" fill="var(--text)" fontSize="10" fontWeight="600">Webhooks</text>
        <rect x="82" y="58" width="64" height="22" rx="6" fill="var(--surface-2)" />
        <text x="114" y="73" textAnchor="middle" fill="var(--text)" fontSize="10" fontWeight="600">REST API</text>
        <rect x="14" y="86" width="132" height="22" rx="6" fill="var(--surface-2)" />
        <text x="80" y="101" textAnchor="middle" fill="var(--text)" fontSize="10" fontWeight="600">Engine de fluxos</text>
      </g>
      {/* DB + Queue */}
      <g transform="translate(400,40)">
        <rect width="100" height="56" rx="14" fill="var(--surface)" stroke="var(--line-strong)" />
        <text x="50" y="24" textAnchor="middle" fill="var(--text)" fontSize="12" fontWeight="700">Postgres</text>
        <text x="50" y="40" textAnchor="middle" fill="var(--text-soft)" fontSize="10">Supabase</text>
      </g>
      <g transform="translate(400,110)">
        <rect width="100" height="56" rx="14" fill="var(--surface)" stroke="var(--line-strong)" />
        <text x="50" y="24" textAnchor="middle" fill="var(--text)" fontSize="12" fontWeight="700">Redis</text>
        <text x="50" y="40" textAnchor="middle" fill="var(--text-soft)" fontSize="10">filas + cache</text>
      </g>
      <g transform="translate(400,180)">
        <rect width="100" height="56" rx="14" fill="var(--surface)" stroke="var(--cyan)" strokeWidth="2" />
        <text x="50" y="24" textAnchor="middle" fill="var(--text)" fontSize="12" fontWeight="700">Frontend</text>
        <text x="50" y="40" textAnchor="middle" fill="var(--text-soft)" fontSize="10">(este app)</text>
      </g>
      {/* Arrows */}
      <path d="M140 62 C 170 62, 180 110, 200 110" stroke="var(--text-mute)" strokeWidth="1.5" fill="none" markerEnd="url(#ah)" />
      <path d="M140 140 C 170 140, 180 140, 200 140" stroke="var(--text-mute)" strokeWidth="1.5" fill="none" markerEnd="url(#ah)" />
      <path d="M140 218 C 170 218, 180 170, 200 170" stroke="var(--text-mute)" strokeWidth="1.5" fill="none" markerEnd="url(#ah)" />
      <path d="M360 110 C 380 110, 380 68, 400 68" stroke="var(--text-mute)" strokeWidth="1.5" fill="none" markerEnd="url(#ah)" />
      <path d="M360 140 C 380 140, 380 138, 400 138" stroke="var(--text-mute)" strokeWidth="1.5" fill="none" markerEnd="url(#ah)" />
      <path d="M360 180 C 380 180, 380 208, 400 208" stroke="var(--text-mute)" strokeWidth="1.5" fill="none" markerEnd="url(#ah)" />
    </svg>
  );
}

function CodeBlock({ title, children }) {
  const [copied, setCopied] = React.useState(false);
  const copy = async () => {
    try { await navigator.clipboard.writeText(children); setCopied(true); setTimeout(() => setCopied(false), 1500); } catch {}
  };
  return (
    <div className="rm-code">
      <div className="rm-code-head">
        <span>{title}</span>
        <button className="btn btn-sm btn-ghost" onClick={copy}>
          {copied ? <><Icons.Check size={12} /> Copiado</> : <><Icons.Copy size={12} /> Copiar</>}
        </button>
      </div>
      <pre>{children}</pre>
    </div>
  );
}

function Timeline() {
  const weeks = [
    { w: 1, t: 'Setup', items: ['Repo + deploy básico (Railway)', 'Banco Postgres', 'Login + workspaces', 'Solicitar revisão Meta'] },
    { w: 2, t: 'Conexão Instagram', items: ['OAuth com Meta', 'Receber webhooks de comentário', 'Endpoint de envio de DM', 'Persistir conversa no banco'] },
    { w: 3, t: 'Engine de fluxos', items: ['CRUD de automações', 'Executor (palavra-chave → enviar DM)', 'Fila com BullMQ', 'Dashboard de runs'] },
    { w: 4, t: 'Polimento', items: ['Conectar com este frontend', 'WhatsApp Cloud API', 'Cobrança Stripe', 'Beta com 10 usuários'] },
  ];
  return (
    <div className="rm-timeline">
      {weeks.map((w) => (
        <div key={w.w} className="rm-week">
          <div className="rm-week-head">
            <div className="rm-week-num">Sem {w.w}</div>
            <div className="rm-week-title">{w.t}</div>
          </div>
          <ul>{w.items.map((it) => <li key={it}><Icons.Check size={12} /> {it}</li>)}</ul>
        </div>
      ))}
    </div>
  );
}

const roadmapStyles = `
.rm-hero {
  display: grid;
  grid-template-columns: 1fr 1.1fr;
  gap: 24px;
  padding: 28px;
  border-radius: var(--radius-lg);
  background: linear-gradient(135deg, color-mix(in oklch, var(--grape) 14%, var(--surface)) 0%, color-mix(in oklch, var(--cyan) 12%, var(--surface)) 100%);
  border: 1px solid var(--line);
  box-shadow: var(--shadow-card);
}
.rm-hero h2 { margin: 6px 0 10px; font-size: 24px; font-weight: 800; letter-spacing: -0.02em; }
.rm-hero p { margin: 0; color: var(--text-soft); font-size: 14px; line-height: 1.55; }
.rm-arch { background: var(--surface); border-radius: var(--radius); padding: 8px; }
@media (max-width: 980px) { .rm-hero { grid-template-columns: 1fr; } }

.rm-grid { display: grid; grid-template-columns: 1.2fr 1fr; gap: 14px; }
@media (max-width: 980px) { .rm-grid { grid-template-columns: 1fr; } }

.rm-card { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 22px; box-shadow: var(--shadow-card); display: flex; flex-direction: column; gap: 14px; }
.rm-card-head { display: flex; align-items: center; gap: 10px; }
.rm-card-head h3 { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: -0.01em; }
.rm-emoji { width: 36px; height: 36px; border-radius: 10px; background: var(--surface-2); display: flex; align-items: center; justify-content: center; font-size: 18px; }

.rm-table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
.rm-table th { text-align: left; font-weight: 600; color: var(--text-soft); padding: 8px 0; width: 30%; vertical-align: top; }
.rm-table td { padding: 8px 0; border-top: 1px dashed var(--line); color: var(--text); line-height: 1.5; }
.rm-table tr:first-child td, .rm-table tr:first-child th { border-top: 0; }
.rm-table code { font-family: var(--font-mono); font-size: 11.5px; padding: 1px 6px; background: var(--surface-2); border-radius: 5px; color: var(--coral); }

.rm-cost-tier { padding: 14px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface-2); display: flex; flex-direction: column; gap: 6px; }
.rm-cost-name { font-weight: 700; font-size: 13.5px; }
.rm-cost-amount { font-size: 22px; font-weight: 800; letter-spacing: -0.02em; }
.rm-cost-amount .muted { font-size: 13px; font-weight: 500; }
.rm-cost-tier ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; color: var(--text-soft); font-size: 12.5px; }
.rm-cost-tier li::before { content: "•"; color: var(--grape); margin-right: 6px; }

.rm-steps { padding-left: 0; margin: 0; counter-reset: step; list-style: none; display: flex; flex-direction: column; gap: 10px; }
.rm-steps li { padding: 10px 14px 10px 44px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface-2); font-size: 13.5px; line-height: 1.5; position: relative; counter-increment: step; }
.rm-steps li::before {
  content: counter(step); position: absolute; left: 12px; top: 12px;
  width: 22px; height: 22px; border-radius: 50%;
  background: var(--grape); color: #fff; font-weight: 700; font-size: 11.5px;
  display: flex; align-items: center; justify-content: center;
}
.rm-steps code { font-family: var(--font-mono); font-size: 11.5px; padding: 1px 5px; background: var(--surface); border-radius: 5px; color: var(--coral); border: 1px solid var(--line); }
.rm-warn { display: inline-block; margin-left: 6px; font-size: 11.5px; font-weight: 600; padding: 2px 8px; background: color-mix(in oklch, var(--sun) 16%, var(--surface)); color: var(--sun); border-radius: 999px; }

.rm-code { border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
.rm-code-head { display: flex; justify-content: space-between; align-items: center; padding: 8px 14px; background: var(--surface-2); border-bottom: 1px solid var(--line); font-size: 12px; font-weight: 600; color: var(--text-soft); }
.rm-code pre { margin: 0; padding: 14px 16px; font-family: var(--font-mono); font-size: 12px; line-height: 1.55; color: var(--text); overflow-x: auto; background: var(--surface); white-space: pre; }

.rm-timeline { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }
@media (max-width: 900px) { .rm-timeline { grid-template-columns: 1fr 1fr; } }
.rm-week { border: 1px solid var(--line); border-radius: 12px; padding: 14px; background: var(--surface-2); display: flex; flex-direction: column; gap: 10px; }
.rm-week-head { display: flex; align-items: baseline; gap: 8px; }
.rm-week-num { font-size: 11px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; padding: 2px 8px; border-radius: 999px; background: color-mix(in oklch, var(--grape) 14%, var(--surface)); color: var(--grape); }
.rm-week-title { font-weight: 700; font-size: 14px; }
.rm-week ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: 12.5px; color: var(--text-soft); }
.rm-week li { display: flex; align-items: center; gap: 6px; }
.rm-week svg { color: var(--green); flex-shrink: 0; }

.rm-cta { background: linear-gradient(135deg, color-mix(in oklch, var(--coral) 12%, var(--surface)), color-mix(in oklch, var(--grape) 10%, var(--surface))); }
.rm-cta h3 { font-size: 16px; }
`;

window.Roadmap = Roadmap;
