// Interactive Prospector demo — the hero's right panel
// Auto-types a query, streams in fake leads, shows SEO scores and a "generate web" step.
// This is the CRO centerpiece — visitors see EXACTLY what the product does in 8 seconds.

const DEMO_QUERY = 'fontanero Burgos';
const DEMO_LEADS = [
  { name: 'Fontanería García e Hijos SL', area: 'Burgos centro · Pol. Villalonquéjar', rating: 4.2, reviews: 28, seo: 22, web: 'lenta', mail: true, phone: '947 26 ··· ··', city: 'Burgos' },
  { name: 'Urgencias Fontaneras 24h Burgos', area: 'Burgos · Capiscol', rating: 4.6, reviews: 84, seo: 14, web: 'sin web', mail: true, phone: '947 21 ··· ··', city: 'Burgos' },
  { name: 'Reparaciones FontaCenter', area: 'Burgos · Gamonal', rating: 3.9, reviews: 12, seo: 31, web: 'lenta', mail: true, phone: '687 ·· ·· ··', city: 'Burgos' },
  { name: 'Fontanero Vena Express', area: 'Burgos · San Pedro de la Fuente', rating: 4.4, reviews: 41, seo: 18, web: 'obsoleta', mail: true, phone: '947 20 ··· ··', city: 'Burgos' },
  { name: 'Instalaciones Hidráulicas Burgos', area: 'Burgos · Pol. Villayuda', rating: 4.7, reviews: 156, seo: 36, web: 'lenta', mail: true, phone: '947 27 ··· ··', city: 'Burgos' },
  { name: 'Fontanería Castilla Norte', area: 'Burgos · G-3', rating: 4.1, reviews: 19, seo: 25, web: 'sin web', mail: true, phone: '947 22 ··· ··', city: 'Burgos' },
  { name: 'AquaPro Burgos', area: 'Burgos · Las Huelgas', rating: 4.5, reviews: 67, seo: 41, web: 'obsoleta', mail: false, phone: '947 23 ··· ··', city: 'Burgos' },
  { name: 'Fontaneros del Arlanzón', area: 'Burgos · Cortes', rating: 4.0, reviews: 23, seo: 29, web: 'sin web', mail: true, phone: '687 ·· ·· ··', city: 'Burgos' },
];

function useTypewriter(text, speed = 55, start = true, delay = 400) {
  const [out, setOut] = React.useState('');
  const [done, setDone] = React.useState(false);
  React.useEffect(() => {
    if (!start) return;
    setOut(''); setDone(false);
    let i = 0; let timer;
    const startT = setTimeout(function tick() {
      if (i <= text.length) {
        setOut(text.slice(0, i));
        i++;
        timer = setTimeout(tick, speed);
      } else {
        setDone(true);
      }
    }, delay);
    return () => { clearTimeout(startT); clearTimeout(timer); };
  }, [text, speed, start, delay]);
  return [out, done];
}

function ProspectorDemo() {
  const [phase, setPhase] = React.useState('typing'); // typing → searching → results → generating → done
  const [leadCount, setLeadCount] = React.useState(0);
  const [selected, setSelected] = React.useState(null);
  const [genStep, setGenStep] = React.useState(0); // 0..4
  const [cycle, setCycle] = React.useState(0);
  const [query, qDone] = useTypewriter(DEMO_QUERY, 65, phase === 'typing', 500);

  // Phase machine
  React.useEffect(() => {
    if (phase === 'typing' && qDone) {
      const t = setTimeout(() => setPhase('searching'), 400);
      return () => clearTimeout(t);
    }
    if (phase === 'searching') {
      const t = setTimeout(() => { setPhase('results'); setLeadCount(1); }, 900);
      return () => clearTimeout(t);
    }
    if (phase === 'results') {
      if (leadCount < DEMO_LEADS.length) {
        const t = setTimeout(() => setLeadCount(c => c + 1), 220);
        return () => clearTimeout(t);
      } else {
        const t = setTimeout(() => { setSelected(1); setPhase('generating'); setGenStep(0); }, 1100);
        return () => clearTimeout(t);
      }
    }
    if (phase === 'generating') {
      if (genStep < 4) {
        const t = setTimeout(() => setGenStep(s => s + 1), 700);
        return () => clearTimeout(t);
      } else {
        const t = setTimeout(() => setPhase('done'), 600);
        return () => clearTimeout(t);
      }
    }
    if (phase === 'done') {
      const t = setTimeout(() => {
        // reset and loop
        setPhase('typing'); setLeadCount(0); setSelected(null); setGenStep(0);
        setCycle(c => c + 1);
      }, 5500);
      return () => clearTimeout(t);
    }
  }, [phase, qDone, leadCount, genStep]);

  return (
    <div style={{
      borderRadius: 22,
      background: '#fff',
      boxShadow: '0 30px 80px -30px rgba(60,24,140,.45), 0 8px 24px -8px rgba(60,24,140,.18)',
      border: '1px solid var(--pl-border)',
      overflow: 'hidden',
      width: '100%',
      maxWidth: 620,
    }}>
      {/* Window chrome */}
      <div style={{
        height: 38, display: 'flex', alignItems: 'center', gap: 8,
        padding: '0 14px',
        background: 'linear-gradient(180deg, #f7f5ff 0%, #efeaff 100%)',
        borderBottom: '1px solid var(--pl-border)',
      }}>
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#fb6f6f' }} />
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#fbcb55' }} />
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#5bd97a' }} />
        <span style={{ marginLeft: 12, fontFamily: 'var(--pl-font-mono)', fontSize: 11, color: 'var(--pl-ink-mute)' }}>
          app.pillaleads.com / prospector
        </span>
        <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6,
          fontSize: 11, fontWeight: 700, color: 'var(--pl-accent-deep)',
          background: 'rgba(124,58,237,.10)', padding: '3px 9px', borderRadius: 999,
        }}>
          <span className="pl-pill-pulse" style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--pl-success)' }} />
          DEMO EN VIVO
        </span>
      </div>

      {/* Search */}
      <div style={{ padding: '14px 16px 8px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          background: '#f7f5ff', border: '1px solid var(--pl-border-strong)',
          borderRadius: 12, padding: '10px 14px',
        }}>
          <IconSearch size={17} color="var(--pl-accent-deep)" />
          <span style={{
            fontFamily: 'var(--pl-font-mono)', fontSize: 14.5,
            color: 'var(--pl-ink)', fontWeight: 500,
          }}>
            {query}
            {phase === 'typing' && (
              <span style={{ display: 'inline-block', width: 1.5, height: 16, background: 'var(--pl-accent)', marginLeft: 2, verticalAlign: -3, animation: 'pl-caret 0.9s steps(1) infinite' }} />
            )}
          </span>
          <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 4,
            fontSize: 11, color: 'var(--pl-ink-mute)', fontWeight: 600 }}>
            <span style={{ background: '#fff', border: '1px solid var(--pl-border)', padding: '2px 6px', borderRadius: 6, fontFamily: 'var(--pl-font-mono)' }}>⏎</span>
            <span>buscar</span>
          </span>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 12, padding: '0 4px' }}>
          <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <Chip active>Google Maps</Chip>
            <Chip>SERP</Chip>
            <Chip>Scoring SEO</Chip>
            <Chip>Email finder</Chip>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--pl-ink-mute)', fontWeight: 600 }}>
            {phase === 'searching' && <SearchingDots />}
            {(phase === 'results' || phase === 'generating' || phase === 'done') && (
              <span><b style={{ color: 'var(--pl-ink)' }}>{DEMO_LEADS.length}</b> leads · <b style={{ color: 'var(--pl-success)' }}>{DEMO_LEADS.filter(l => l.mail).length}</b> con email</span>
            )}
          </div>
        </div>
      </div>

      {/* Leads list */}
      <div className="pl-scroll" style={{
        padding: '8px 16px 12px',
        maxHeight: 320, overflowY: 'auto',
        background: 'linear-gradient(180deg, #fff 0%, #fbfaff 100%)',
        position: 'relative',
      }}>
        {DEMO_LEADS.slice(0, leadCount).map((l, i) => (
          <LeadRow key={cycle + '-' + i} lead={l} index={i} highlighted={selected === i} />
        ))}
        {leadCount === 0 && phase !== 'typing' && (
          <div style={{ padding: '32px 0', textAlign: 'center', color: 'var(--pl-ink-mute)', fontSize: 13 }}>
            <SearchingDots /> Scrapeando Google Maps + analizando SEO de cada web…
          </div>
        )}
        {phase === 'typing' && (
          <div style={{ padding: '60px 0', textAlign: 'center', color: 'var(--pl-ink-mute)', fontSize: 13 }}>
            Escribe categoría + ciudad para empezar
          </div>
        )}
      </div>

      {/* Action bar / generation */}
      <div style={{
        borderTop: '1px solid var(--pl-border)',
        padding: '14px 16px',
        background: phase === 'done' ? '#f0fdf4' : '#fafafa',
        transition: 'background .3s',
      }}>
        {phase !== 'generating' && phase !== 'done' && (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
            <div style={{ fontSize: 13, color: 'var(--pl-ink-3)' }}>
              👉 Selecciona un lead y se le genera <b style={{ color: 'var(--pl-ink)' }}>web + email + script</b> en 30s.
            </div>
            <button className="pl-btn pl-btn-accent pl-btn-sm" disabled style={{ opacity: leadCount >= DEMO_LEADS.length ? 1 : .4 }}>
              <IconWand size={14} /> Generar web
            </button>
          </div>
        )}
        {(phase === 'generating' || phase === 'done') && (
          <GenSteps step={phase === 'done' ? 5 : genStep} lead={DEMO_LEADS[1]} />
        )}
      </div>

      <style>{`
        @keyframes pl-caret { 50% { opacity: 0; } }
        @keyframes pl-row-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
        @keyframes pl-dot { 0%, 80%, 100% { opacity: .2; } 40% { opacity: 1; } }
      `}</style>
    </div>
  );
}

function Chip({ children, active }) {
  return (
    <span style={{
      fontSize: 11, fontWeight: 700, letterSpacing: '.02em',
      padding: '4px 9px', borderRadius: 999,
      background: active ? 'var(--pl-accent)' : '#fff',
      color: active ? '#fff' : 'var(--pl-ink-3)',
      border: active ? '1px solid var(--pl-accent)' : '1px solid var(--pl-border)',
    }}>{children}</span>
  );
}

function SearchingDots() {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
      <span style={{ display: 'inline-flex', gap: 3 }}>
        {[0,1,2].map(i => (
          <span key={i} style={{
            width: 4, height: 4, borderRadius: '50%', background: 'var(--pl-accent)',
            animation: `pl-dot 1.4s ${i*0.18}s infinite ease-in-out`,
          }} />
        ))}
      </span>
      <span>buscando</span>
    </span>
  );
}

function LeadRow({ lead, index, highlighted }) {
  const seoColor = lead.seo < 25 ? '#dc2626' : lead.seo < 40 ? '#ea580c' : '#ca8a04';
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr auto auto',
      gap: 12, alignItems: 'center',
      padding: '11px 12px',
      borderRadius: 12,
      background: highlighted ? 'linear-gradient(90deg, rgba(124,58,237,.10), rgba(124,58,237,0))' : 'transparent',
      borderBottom: '1px solid var(--pl-border)',
      transition: 'background .2s',
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{
            fontSize: 13.5, fontWeight: 700, color: 'var(--pl-ink)',
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{lead.name}</span>
          {highlighted && (
            <span style={{
              fontSize: 9.5, fontWeight: 800, letterSpacing: '.08em',
              padding: '2px 6px', borderRadius: 5,
              background: 'var(--pl-accent)', color: '#fff',
            }}>SELECCIONADO</span>
          )}
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--pl-ink-mute)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 8 }}>
          <span>{lead.area}</span>
          <span>·</span>
          <span style={{ color: '#ca8a04' }}>★ {lead.rating} <span style={{ color: 'var(--pl-ink-mute)' }}>({lead.reviews})</span></span>
          {lead.mail && (<>
            <span>·</span>
            <span style={{ color: 'var(--pl-success)', fontWeight: 600 }}>✓ email</span>
          </>)}
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4 }}>
        <span style={{
          fontSize: 10, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase',
          color: lead.web === 'sin web' ? '#dc2626' : '#ea580c',
        }}>{lead.web}</span>
        <span style={{
          fontSize: 11, fontWeight: 700, fontFamily: 'var(--pl-font-mono)',
          color: seoColor,
          background: seoColor + '15',
          padding: '2px 7px', borderRadius: 6,
        }}>SEO {lead.seo}</span>
      </div>
      <button style={{
        appearance: 'none', border: '1px solid var(--pl-border-strong)',
        background: '#fff', borderRadius: 8, padding: '6px 10px',
        fontSize: 11.5, fontWeight: 700, color: 'var(--pl-accent-deep)',
        cursor: 'default',
      }}>Abrir →</button>
    </div>
  );
}

function GenSteps({ step, lead }) {
  const steps = [
    { l: 'Auditoría SEO completada', i: <IconCheck size={14} /> },
    { l: 'Logo + branding extraídos', i: <IconSpark size={14} /> },
    { l: 'Web nueva generada', i: <IconGlobe size={14} /> },
    { l: 'Email + WhatsApp redactados', i: <IconMail size={14} /> },
    { l: 'Listo para enviar', i: <IconBolt size={14} /> },
  ];
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--pl-ink-2)' }}>
          Generando paquete para <span style={{ color: 'var(--pl-accent-deep)' }}>{lead.name}</span>
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--pl-ink-mute)', fontFamily: 'var(--pl-font-mono)' }}>
          {Math.min(step, 5)}/5
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {steps.map((s, i) => {
          const done = i < step;
          const cur = i === step && step < 5;
          return (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              fontSize: 12.5,
              color: done ? 'var(--pl-success)' : cur ? 'var(--pl-accent-deep)' : 'var(--pl-ink-mute)',
              fontWeight: done || cur ? 700 : 500,
              opacity: done || cur ? 1 : .55,
            }}>
              <span style={{
                width: 18, height: 18, borderRadius: '50%',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                background: done ? 'rgba(22,163,74,.12)' : cur ? 'rgba(124,58,237,.12)' : 'rgba(0,0,0,.04)',
                color: 'currentColor',
              }}>
                {done ? <IconCheck size={11} stroke={3} /> : cur ? <span className="pl-pill-pulse" style={{ width: 6, height: 6, borderRadius: '50%', background: 'currentColor' }} /> : null}
              </span>
              {s.l}
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { ProspectorDemo });
