const { Button, NavBar, SectionHeader, Footer, Card, Input } = window.FasiDesignSystem_22efce;
const { useState, useEffect } = React;

const LOGO = 'assets/logo-fasi.png';
const LOGO_WHITE = 'assets/logo-fasi-white.png';
const LOGO_INK = 'assets/logo-fasi-ink.png';
const NAV_LINKS = [{ label: 'Trabajo', href: '#work' }, { label: 'Servicios', href: '#services' }, { label: 'Conecta', href: '#connect' }];

function useMedia(q) {
  const [m, set] = useState(() => window.matchMedia(q).matches);
  useEffect(() => { const mq = window.matchMedia(q); const h = () => set(mq.matches); mq.addEventListener('change', h); return () => mq.removeEventListener('change', h); }, [q]);
  return m;
}

function useScrolled(px) {
  const [s, set] = useState(false);
  useEffect(() => { const h = () => set(window.scrollY > px); h(); window.addEventListener('scroll', h, { passive: true }); return () => window.removeEventListener('scroll', h); }, [px]);
  return s;
}

function useReveal() {
  useEffect(() => {
    const els = Array.from(document.querySelectorAll('[data-reveal]'));
    if (!('IntersectionObserver' in window) || window.matchMedia('(prefers-reduced-motion:reduce)').matches) { els.forEach((e) => e.classList.add('in')); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.06 });
    els.forEach((e) => io.observe(e));
    const sweep = () => els.forEach((e) => {
      if (e.classList.contains('in')) return;
      const r = e.getBoundingClientRect();
      if (r.top < window.innerHeight && r.bottom > 0) { e.classList.add('in'); io.unobserve(e); }
    });
    const raf = requestAnimationFrame(sweep);
    const t = setTimeout(sweep, 900);
    return () => { cancelAnimationFrame(raf); clearTimeout(t); io.disconnect(); };
  }, []);
}

function Nav() {
  const scrolled = useScrolled(16);
  const compact = useMedia('(max-width:820px)');
  return (
    <div className={"nav-fixed" + (scrolled ? "" : " over-hero")}>
      <NavBar
        logoSrc={scrolled ? LOGO : LOGO_INK}
        brand="Fasi"
        links={compact ? [] : NAV_LINKS}
        cta="Contactar"
        ctaHref="#contact"
        style={{
          maxWidth: 'none',
          background: scrolled ? 'rgba(255,255,255,.92)' : 'transparent',
          backdropFilter: scrolled ? 'blur(8px)' : 'none',
          borderBottomColor: scrolled ? 'var(--border-subtle)' : 'transparent',
          transition: 'background-color var(--duration-base) var(--ease-standard),border-color var(--duration-base) var(--ease-standard)'
        }}
      />
    </div>
  );
}

function Hero() {
  return (
    <section className="wrap hero">
      <div className="hero-head">
        <span className="eyebrow">Diseño de páginas web para negocios en todo México.</span>
        <div className="hero-head-block">
          <h1 className="hero-title"><span className="ln"><span>Una página web.</span></span><span className="ln"><span>Miles de clientes que no viste.</span></span></h1>
        </div>
      </div>
      <img className="hero-mark" src="assets/symbol-fasi-ink.png" alt="" aria-hidden="true" />
      <div className="g12 hero-foot">
        <div className="hero-support">
          <p className="line" style={{ fontSize: 'var(--text-body-size)', lineHeight: 'var(--text-body-lh)' }}>Empieza ahora<br />y lleva tu negocio al nivel superior.</p>
          <Button variant="primary" size="lg" href="#contact" style={{ background: 'var(--ink-900)', color: 'var(--surface-page)', borderColor: 'var(--ink-900)' }}>Empezar el proyecto</Button>
        </div>
      </div>
    </section>
  );
}

const NEEDS = [
  { id: 'need-1', pos: 'br', title: 'Ahora la presencia digital lo es TODO', line: 'En este momento, tener tu negocio en internet genera un 145% más de ganancias' },
  { id: 'need-2', pos: 'bl', title: 'Venderás hasta por dormir', line: 'Si está tu página online 24/7, recibirás clientes y ganarás dinero dentro y fuera de tu negocio.' },
  { id: 'need-3', pos: 'br', title: 'En redes tu tienes que administrar todo, en tu página, solo mueves la batuta.', line: 'En las redes sociales tú tienes que publicar todos los días y esperar a tener suerte para que algo sea viral. Con tu página, puedes actualizar TODOS los días y sin que muevas un dedo.' },
  { id: 'need-4', pos: 'bl', title: 'Clientes que ni siquiera conocías, vendrán a ti', line: 'Personas de otras partes del país y del mundo conocerán tu negocio, y por supuesto comprarán a través de él.' }
];

function Needs() {
  return (
    <section id="services" className="sect sect-needs glow-top" style={{ background: 'var(--surface-alt)' }}>
      <div className="wrap">
        <div className="needs-head" data-reveal>
          <h2 className="needs-title">¿Por qué necesitas una página web YA MISMO?</h2>
          <p className="needs-sub">(Antes de que sea tarde)</p>
        </div>
        <div className="needs-grid">
          {NEEDS.map((s) => (
            <div className={'need-card ' + s.pos} key={s.id} data-reveal>
              <div className="need-body">
                <h3>{s.title}</h3>
                <p className="line">{s.line}</p>
              </div>
              <div className="need-media">
                <image-slot id={s.id} shape="rect" fit="cover" placeholder="Imagen"></image-slot>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

const CONNECT = [
  { src: 'assets/logos/rappi.png', alt: 'Rappi' },
  { src: 'assets/logos/gmail.png', alt: 'Gmail' },
  { src: 'assets/logos/shopify.png', alt: 'Shopify' },
  { src: 'assets/logos/didi.svg', alt: 'DiDi' },
  { src: 'assets/logos/instagram.png', alt: 'Instagram' },
  { src: 'assets/logos/paypal.png', alt: 'PayPal' },
  { src: 'assets/logos/youtube.png', alt: 'YouTube' },
  { src: 'assets/logos/fasi.png', alt: 'Fasi' },
  { src: 'assets/logos/ubereats.png', alt: 'Uber Eats' },
  { src: 'assets/logos/linkedin.png', alt: 'LinkedIn' },
  { src: 'assets/logos/mercadopago.png', alt: 'Mercado Pago' },
  { src: 'assets/logos/whatsapp.png', alt: 'WhatsApp' },
  { src: 'assets/logos/opentable.png', alt: 'OpenTable' },
  { src: 'assets/logos/stripe.png', alt: 'Stripe' },
  { src: 'assets/logos/facebook.png', alt: 'Facebook' }
];

function Process() {
  const copies = 8;
  const row = [];
  for (let i = 0; i < copies; i++) row.push(...CONNECT);
  return (
    <section id="connect" className="sect sect-connect" style={{ background: 'var(--surface-dark)' }}>
      <div className="wrap connect-head" data-reveal>
        <h2 className="connect-title">Conecta todo en UN solo lugar</h2>
        <p className="connect-intro">Conecta en tu página web:</p>
      </div>
      <div className="marquee" data-reveal>
        <div className="marquee-track">
          {row.map((l, i) => (
            <img className="marquee-logo" src={l.src} alt={i < CONNECT.length ? l.alt : ''} aria-hidden={i >= CONNECT.length ? 'true' : undefined} key={l.alt + i} />
          ))}
        </div>
      </div>
      <div className="wrap connect-foot" data-reveal>
        <p className="line on-dark">¿Habías imaginado el poder promocionar y poder recibir pagos desde una sola página? Bueno, encontraste EL lugar indicado.</p>
      </div>
    </section>
  );
}

const GRID_V = [80, 165, 250, 335, 420, 505, 590, 675, 760, 845, 930];
const GRID_H = [183.4, 269.7, 356, 442.3];
const TICKS = [{ v: '3,500', y: 442.3, alt: true }, { v: '4,500', y: 269.7 }, { v: '5,000', y: 183.4, alt: true }];

function GrowthChart() {
  return (
    <div className="growth-slot" data-reveal>
      <svg className="gchart" viewBox="-80 0 1080 560" preserveAspectRatio="xMidYMid meet" role="img" aria-label="Los clientes se mantienen planos en 3,861 al mes sin sitio web y llegan a 5,367, un 39 % más, después de publicarlo">
        <g className="g-grid">
          {GRID_V.map((x) => (<line key={'v' + x} x1={x} y1="60" x2={x} y2="470" />))}
          {GRID_H.map((y) => (<line key={'h' + y} x1="80" y1={y} x2="948" y2={y} />))}
        </g>
        <line className="g-guide" x1="80" y1="380" x2="920" y2="380" />
        <line className="g-guide" x1="80" y1="120" x2="920" y2="120" />
        <line className="g-axis" x1="80" y1="56" x2="80" y2="470" />
        <line className="g-axis" x1="80" y1="470" x2="948" y2="470" />
        <path className="g-before" pathLength="1" d="M 92 374 C 160 366 212 392 292 394 S 432 386 520 380" />
        <line className="g-mark" pathLength="1" x1="520" y1="470" x2="520" y2="252" />
        <circle className="g-dot" cx="520" cy="380" r="10" />
        <path className="g-after" pathLength="1" d="M 520 380 C 620 378 680 336 730 280 C 790 214 850 168 902 132" />
        <polygon className="g-arrow" points="920.1,119.5 907.6,146.4 890.5,121.7" />
        <g className="g-ticks">
          {TICKS.map((t) => (<line key={'t' + t.y} className={t.alt ? 'g-tick-alt' : undefined} x1="72" y1={t.y} x2="80" y2={t.y} />))}
          {TICKS.map((t) => (<text key={'l' + t.y} className={'g-tick' + (t.alt ? ' g-tick-alt' : '')} x="64" y={t.y + 6} textAnchor="end">{t.v}</text>))}
        </g>
        <line className="g-tick-mark g-tick-base" x1="72" y1="380" x2="80" y2="380" />
        <text className="g-tick g-tick-base" x="64" y="386" textAnchor="end">3,861</text>
        <line className="g-tick-mark g-tick-hi" x1="72" y1="120" x2="80" y2="120" />
        <text className="g-tick g-tick-hi" x="64" y="126" textAnchor="end">5,367</text>
        <text className="g-mark-t" x="520" y="200" textAnchor="middle"><tspan x="520">EL momento en que</tspan><tspan x="520" dy="1.25em">publicas tu página web</tspan></text>
        <text className="g-seg g-seg-a" x="250" y="434" textAnchor="middle">Sin sitio web</text>
        <text className="g-seg g-seg-b" x="742" y="434" textAnchor="middle">Con sitio web</text>
        <text className="g-eyebrow" x="898" y="48" textAnchor="end">DE 3,861 A</text>
        <text className="g-big" x="898" y="96" textAnchor="end">5,367</text>
        <text className="g-axis-t" x="80" y="38">Clientes al mes</text>
        <text className="g-axis-t g-axis-x" x="948" y="502" textAnchor="end">Tiempo</text>
      </svg>
    </div>
  );
}

function Why() {
  return (
    <section className="sect">
      <div className="wrap growth">
        <div className="growth-head" data-reveal>
          <SectionHeader eyebrow="Antes y después" title="Los negocios sin sitio web pierden hasta 1 de cada 3 clientes" size="h2" />
        </div>
        <GrowthChart />
      </div>
    </section>
  );
}

const WORK = [
  { id: 'work-1', name: 'Marea', meta: 'Restaurante · 2026', wide: true },
  { id: 'work-2', name: 'Talleres Nova', meta: 'Servicios · 2025' },
  { id: 'work-3', name: 'Vera Clinic', meta: 'Salud · 2025' }
];

function Work() {
  return (
    <section id="work" className="sect" style={{ background: 'var(--surface-alt)' }}>
      <div className="wrap">
        <SectionHeader eyebrow="Trabajo reciente" title="Nuestros mejores clientes enmarcados en nuestra página." size="h2" data-reveal />
        <div className="work-grid" style={{ marginTop: 'clamp(var(--space-64),7vw,var(--space-96))' }}>
          {WORK.map((w) => (
            <div className={'work-item' + (w.wide ? ' wide' : '')} key={w.id} data-reveal>
              <div className="work-shot">
                <image-slot id={w.id} shape="rect" fit="cover" placeholder="Suelta una captura"></image-slot>
              </div>
              <div className="work-cap">
                <strong>{w.name}</strong>
                <span>{w.meta}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

const QUIZ = [
  { q: '¿Cuál es tu negocio?', options: ['Restaurante / Café', 'Venta de producto', 'Servicio online', 'Otro'], label: 'Negocio' },
  { q: '¿Qué te interesa más que tenga tu página web?', options: ['Animaciones increíbles', 'Fácil de usar', 'Diseños originales', 'Otro'], label: 'Me interesa' },
  { q: '¿Cuentas con tu logo y tus recursos digitalizados?', options: ['Sí', 'No', 'No sé'], label: 'Recursos digitalizados' },
  { q: '¿Estás listo para llevar tu negocio al nivel superior?', options: ['Sí, empecemos'], label: 'Listo para empezar', glow: true, heading: (
    <React.Fragment>¿Estás listo para llevar tu negocio al <span className="q-ul">nivel superior<svg className="q-ul-svg" viewBox="0 0 300 22" preserveAspectRatio="none" aria-hidden="true"><path d="M4 13.5C38 7.2 84 4.6 131 5.1c39 .4 78 2.6 116 6.4-33-1.2-66-1.7-99-1.2-38 .5-76 2.7-113 6.9" fill="none" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" /></svg></span>?</React.Fragment>
  ) },
  { q: '¿A dónde nos comunicamos para comenzar?', type: 'contact', label: 'Contacto' }
];

function Triangles() {
  return (
    <div className="q-tris" aria-hidden="true">
      <span className="q-tri q-tri-a"><svg viewBox="0 0 100 100" fill="none"><path d="M18 8 L82 34 L34 92 Z" stroke="currentColor" strokeWidth="5" strokeLinejoin="round" /></svg></span>
      <span className="q-tri q-tri-b"><svg viewBox="0 0 100 100" fill="none"><path d="M50 14 L90 86 L10 86 Z" fill="currentColor" /></svg></span>
      <span className="q-tri q-tri-c"><svg viewBox="0 0 100 100" fill="none"><path d="M18 8 L82 34 L34 92 Z" stroke="currentColor" strokeWidth="5" strokeLinejoin="round" /></svg></span>
      <span className="q-tri q-tri-d"><svg viewBox="0 0 100 100" fill="none"><path d="M50 14 L90 86 L10 86 Z" fill="currentColor" /></svg></span>
    </div>
  );
}

function Contact() {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState([]);
  const [out, setOut] = React.useState(false);
  const [contact, setContact] = React.useState('');
  const [channel, setChannel] = React.useState(null);
  const [contactErr, setContactErr] = React.useState('');
  const done = step >= QUIZ.length;
  const pick = (opt) => {
    if (out) return;
    const go = () => { setAnswers((a) => a.concat(opt)); setStep((s) => s + 1); setOut(false); };
    if (window.matchMedia('(prefers-reduced-motion:reduce)').matches) { go(); return; }
    setOut(true);
    setTimeout(go, 280);
  };
  const sendContact = (e) => {
    e.preventDefault();
    const v = contact.trim();
    if (channel === 'Correo' && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v)) { setContactErr('Introduce un correo válido.'); return; }
    if (channel === 'Teléfono' && v.replace(/\D/g, '').length < 8) { setContactErr('Introduce un número de teléfono válido.'); return; }
    setContactErr('');
    pick(v);
  };
  const reset = () => { setAnswers([]); setStep(0); setContact(''); setChannel(null); setContactErr(''); };
  const body = QUIZ.map((q, i) => (i === 4 ? (channel || 'Contacto') : q.label) + ': ' + (answers[i] || '')).join('\n');
  const mail = 'mailto:tryfasicompany@gmail.com?subject=' + encodeURIComponent('Nuevo proyecto') + '&body=' + encodeURIComponent(body + '\n\n');
  const cur = done ? null : QUIZ[step];
  return (
    <section id="contact" style={{ background: 'var(--surface-dark)' }}>
      <div className="wrap contact" data-reveal>
        {done ? (
          <div className="q-step">
            <span className="q-count">Anotado</span>
            <h2>Creemos tu nueva página web.</h2>
            <p className="q-sum">{answers.slice(0, 3).join(' · ')}</p>
            <p className="q-sum">{channel === 'Correo' ? 'Te escribimos a ' : 'Te llamamos al '}{answers[4]}</p>
            <div className="q-end">
              <Button variant="primary" size="lg" href={mail}>Empezar el proyecto</Button>
              <button type="button" className="q-reset" onClick={reset}>Cambiar respuestas</button>
            </div>
          </div>
        ) : (
          <div className={'q-step' + (out ? ' out' : '') + (cur.glow ? ' q-glow' : '')} key={step}>
            {cur.glow ? <Triangles /> : null}
            <span className="q-count">{step + 1} / {QUIZ.length}</span>
            <h2>{cur.heading || cur.q}</h2>
            {cur.type === 'contact' ? (
              <div className="q-ch">
                <div className="q-ch-pick">
                  {['Correo', 'Teléfono'].map((c) => (
                    <button
                      key={c}
                      type="button"
                      className={'q-chip' + (channel === c ? ' on' : '')}
                      aria-pressed={channel === c}
                      onClick={() => { setChannel(c); setContact(''); setContactErr(''); }}
                    >{c}</button>
                  ))}
                </div>
                {channel ? (
                  <form className="q-tel" onSubmit={sendContact} noValidate key={channel}>
                    <Input
                      type={channel === 'Correo' ? 'email' : 'tel'}
                      onDark
                      label={channel}
                      placeholder={channel === 'Correo' ? 'nombre@correo.com' : '+52 55 0000 0000'}
                      value={contact}
                      error={contactErr || undefined}
                      onChange={(e) => { setContact(e.target.value); if (contactErr) setContactErr(''); }}
                    />
                    <Button variant="primary" size="lg" type="submit">Enviar</Button>
                  </form>
                ) : null}
              </div>
            ) : (
              <div className="q-opts">
                {cur.options.map((o) => (
                  <Button key={o} variant="secondary" size="lg" onDark onClick={() => pick(o)}>{o}</Button>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </section>
  );
}

function App() {
  useReveal();
  return (
    <React.Fragment>
      <Nav />
      <main>
        <Hero />
        <Needs />
        <Process />
        <Why />
        <Work />
        <Contact />
      </main>
      <Footer
        className="site-footer"
        logoSrc={LOGO_WHITE}
        claim="Webs a medida, diseñadas y construidas desde cero."
        columns={[
          { title: 'Contacto', links: [{ label: 'tryfasicompany@gmail.com', href: 'mailto:tryfasicompany@gmail.com' }] },
          { title: 'Fasi', links: [
            { label: 'Sobre nosotros', href: '#services' },
            { label: 'FAQ', href: '#' },
            { label: 'Redes Sociales', href: '#' },
            { label: 'Reportar bug', href: 'mailto:tryfasicompany@gmail.com?subject=Reportar%20bug' }
          ] }
        ]}
        legal=""
        legalLinks={[
          { label: 'Política de Privacidad', href: '#' },
          { label: 'Términos y Condiciones', href: '#' }
        ]}
        style={{ borderTop: '1px solid var(--border-on-dark)', paddingTop: 'var(--space-64)' }}
      />
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
