/* links.jsx — Gerador de links de afiliado (substitui o Painel) */
const {
  Button: LkBtn, Input: LkInput, Badge: LkBadge, cn: lkcn,
  IconLink: LkLink, IconCopy: LkCopy, IconCheck: LkCheck, IconExternal: LkExt,
  IconBolt: LkBolt, IconTrash: LkTrash, IconAlert: LkAlert, IconShield: LkShield,
  IconSearch: LkSearch,
} = window;

const LK_PLATFORM = {
  ml: { name: 'Mercado Livre', dot: 'bg-gold', text: 'text-gold', tint: 'rgba(255,208,0,0.10)', host: 'mercadolivre.com/sec/' },
  shopee: { name: 'Shopee', dot: 'bg-coral', text: 'text-coral', tint: 'rgba(249,94,46,0.10)', host: 's.shopee.com.br/' },
};

function lkDetect(url) {
  const u = (url || '').toLowerCase();
  if (/mercadoli(v|b)re|mercadolibre|\/mlb|produto\.merc/.test(u)) return 'ml';
  if (/shopee/.test(u)) return 'shopee';
  return null;
}

function lkShortCode(seed, len) {
  let h = 2166136261;
  for (let i = 0; i < seed.length; i++) { h ^= seed.charCodeAt(i); h = Math.imul(h, 16777619); }
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
  let s = '', x = h >>> 0;
  for (let i = 0; i < (len || 10); i++) { s += chars[x % chars.length]; x = (Math.floor(x / chars.length) + (i + 1) * 7919) >>> 0; }
  return s;
}

/* ---------- Botão copiar ---------- */
function CopyButton({ text, label }) {
  const { useState } = React;
  const [done, setDone] = useState(false);
  const copy = () => {
    const ta = document.createElement('textarea');
    ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0';
    document.body.appendChild(ta); ta.select();
    try { document.execCommand('copy'); } catch (e) {}
    document.body.removeChild(ta);
    setDone(true); setTimeout(() => setDone(false), 1600);
  };
  return (
    <LkBtn onClick={copy} variant={done ? 'default' : 'secondary'} size="sm" className="shrink-0">
      {done ? <><LkCheck size={15} /> Copiado</> : <><LkCopy size={15} /> {label || 'Copiar'}</>}
    </LkBtn>
  );
}

function LinksPage({ apiMl, apiShopee, onConfigApi, onSearch }) {
  const { useState } = React;
  const [url, setUrl] = useState('');
  const [subid, setSubid] = useState('');
  const [err, setErr] = useState('');
  const [result, setResult] = useState(null);
  const [history, setHistory] = useState([]);

  const generate = () => {
    const clean = url.trim();
    if (!clean) { setErr('Cole o link de um produto do Mercado Livre ou da Shopee.'); return; }
    const platform = lkDetect(clean);
    if (!platform) { setErr('Não reconhecemos esse link. Use uma URL de produto do Mercado Livre ou da Shopee.'); return; }
    setErr('');
    const tag = (subid.trim() || 'achamais').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 24) || 'achamais';
    const code = lkShortCode(clean + '|' + tag, 10);
    const link = 'https://' + LK_PLATFORM[platform].host + code;
    const entry = {
      id: code, platform, original: clean, link, subid: tag,
      official: platform === 'ml' ? apiMl : apiShopee,
      time: new Date(),
    };
    setResult(entry);
    setHistory((prev) => [entry, ...prev.filter((e) => e.id !== code)].slice(0, 20));
    setUrl(''); setSubid('');
  };

  const remove = (id) => setHistory((prev) => prev.filter((e) => e.id !== id));

  return (
    <main className="mx-auto w-full max-w-4xl flex-1 px-4 py-7 sm:px-5 sm:py-8">
      <div className="mb-6">
        <div className="flex items-center gap-2">
          <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-brand/12 text-brand"><LkLink size={18} /></span>
          <h1 className="font-syne text-2xl font-extrabold tracking-tight text-white">Gerador de links</h1>
        </div>
        <p className="mt-1.5 text-sm text-zinc-500">Cole o link de um produto e gere seu link de afiliado encurtado, pronto para divulgar.</p>
      </div>

      {/* Gerador */}
      <div className="rounded-2xl border border-edge bg-panel p-4 sm:p-5">
        <label className="mb-1.5 block text-sm font-medium text-zinc-200">Link do produto</label>
        <div className="flex flex-col gap-2 sm:flex-row">
          <div className="relative flex-1">
            <span className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-zinc-500"><LkLink size={17} /></span>
            <LkInput value={url} onChange={(e) => { setUrl(e.target.value); setErr(''); }}
              onKeyDown={(e) => { if (e.key === 'Enter') generate(); }}
              placeholder="https://produto.mercadolivre.com.br/... ou shopee.com.br/..."
              className="h-12 pl-10 text-sm" />
          </div>
          <LkBtn onClick={generate} className="h-12 shrink-0 px-5">Gerar link <LkBolt size={16} /></LkBtn>
        </div>

        <div className="mt-3 flex flex-col gap-2 sm:flex-row sm:items-center">
          <label className="text-xs font-medium text-zinc-400 sm:w-44">Sub-ID / campanha <span className="text-zinc-600">(opcional)</span></label>
          <LkInput value={subid} onChange={(e) => setSubid(e.target.value)} placeholder="ex.: instagram-stories, grupo-whats"
            className="h-10 flex-1 text-sm" />
        </div>

        {err && <div className="mt-3 flex items-start gap-2 rounded-xl border border-coral/30 bg-coral/[0.06] px-3 py-2.5 text-sm text-coral"><span className="mt-0.5 shrink-0"><LkAlert size={15} /></span>{err}</div>}

        {result && (() => {
          const p = LK_PLATFORM[result.platform];
          return (
            <div className="mt-4 overflow-hidden rounded-xl border border-brand/40 bg-brand/[0.05]">
              <div className="flex items-center gap-2 border-b border-brand/20 px-4 py-2.5">
                <span className={lkcn('inline-flex items-center gap-1.5 text-xs font-semibold', p.text)}><span className={lkcn('h-1.5 w-1.5 rounded-full', p.dot)} />{p.name}</span>
                <span className="text-xs text-zinc-500">· sub-id: <span className="font-mono text-zinc-400">{result.subid}</span></span>
                <span className="ml-auto inline-flex items-center gap-1 text-xs font-medium text-brand"><LkCheck size={13} /> Link pronto</span>
              </div>
              <div className="flex flex-col gap-3 p-4 sm:flex-row sm:items-center">
                <code className="min-w-0 flex-1 truncate rounded-lg bg-ink/60 px-3 py-2.5 font-mono text-sm text-zinc-100">{result.link}</code>
                <div className="flex shrink-0 items-center gap-2">
                  <CopyButton text={result.link} label="Copiar link" />
                  <a href={result.original} target="_blank" rel="noopener noreferrer"><LkBtn variant="ghost" size="sm" aria-label="Abrir produto"><LkExt size={15} /></LkBtn></a>
                </div>
              </div>
              {!result.official && (
                <div className="flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-brand/15 px-4 py-2.5 text-xs text-zinc-400">
                  <span className="text-amber-300/90">⚠ {p.name} ainda não conectado.</span>
                  <span>Conecte sua conta para que as comissões sejam creditadas a você.</span>
                  <button onClick={onConfigApi} className="font-semibold text-brand hover:underline">Conectar API</button>
                </div>
              )}
            </div>
          );
        })()}
      </div>

      {/* Histórico */}
      <div className="mt-6">
        <div className="mb-3 flex items-center justify-between">
          <h2 className="text-sm font-semibold text-zinc-300">Seus links gerados {history.length > 0 && <span className="text-zinc-600">({history.length})</span>}</h2>
        </div>

        {history.length === 0 ? (
          <div className="flex flex-col items-center justify-center gap-3 rounded-2xl border border-dashed border-edge py-14 text-center">
            <span className="flex h-14 w-14 items-center justify-center rounded-2xl bg-white/[0.04] text-zinc-600"><LkLink size={24} /></span>
            <p className="max-w-xs text-sm text-zinc-500">Nenhum link gerado ainda. Cole um produto acima ou comece por uma busca.</p>
            <LkBtn variant="secondary" size="sm" onClick={onSearch}><LkSearch size={15} /> Buscar produtos</LkBtn>
          </div>
        ) : (
          <div className="space-y-2">
            {history.map((e) => {
              const p = LK_PLATFORM[e.platform];
              return (
                <div key={e.id} className="flex items-center gap-3 rounded-xl border border-edge bg-panel p-3 sm:gap-4">
                  <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg" style={{ background: p.tint }}>
                    <span className={lkcn('h-2 w-2 rounded-full', p.dot)} />
                  </span>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <code className="truncate font-mono text-sm text-zinc-100">{e.link.replace('https://', '')}</code>
                      {e.subid !== 'achamais' && <span className="hidden shrink-0 rounded bg-white/[0.06] px-1.5 py-0.5 font-mono text-[10px] text-zinc-400 sm:inline">{e.subid}</span>}
                    </div>
                    <div className="mt-0.5 truncate text-xs text-zinc-600">{e.original.replace(/^https?:\/\//, '')}</div>
                  </div>
                  <div className="flex shrink-0 items-center gap-1.5">
                    <CopyButton text={e.link} label="" />
                    <button onClick={() => remove(e.id)} aria-label="Remover" className="flex h-9 w-9 items-center justify-center rounded-lg border border-edge text-zinc-500 transition-colors hover:border-coral/40 hover:text-coral"><LkTrash size={15} /></button>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Nota */}
      <div className="mt-6 flex items-start gap-3 rounded-2xl border border-edge bg-white/[0.02] px-4 py-3.5">
        <span className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand"><LkShield size={16} /></span>
        <p className="text-sm text-zinc-400">Os links curtos apontam direto para o produto com sua marcação de afiliada. Use o <span className="text-zinc-200">sub-id</span> para saber de qual canal veio cada venda — Stories, grupo de WhatsApp, bio do Instagram e por aí vai.</p>
      </div>
    </main>
  );
}

Object.assign(window, { LinksPage });
