// ============================================================
// GARABATO · Shared chrome — Preloader, Nav, Footer, PageHeader,
// ContactForm, Tweaks. Usado en todas las páginas del sitio.
// Lee datos de window.CONTENT (data/content.js).
// ============================================================

const { SITE } = window.CONTENT;

// ──────────────── PRELOADER ────────────────
// Entrada breve: el isotipo real aparece con rebote + bob.
const Preloader = () => {
  const [hidden, setHidden] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setHidden(true), 650);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className={`preloader ${hidden ? 'preloader--hidden' : ''}`} aria-hidden="true">
      <img
        className="preloader__mark"
        src="assets/garabato-logo.png"
        alt=""
        width="200" height="50"
        style={{ width: 200, height: 'auto', objectFit: 'contain', objectPosition: 'left center', clipPath: 'inset(0 75.5% 0 0)' }}
      />
    </div>
  );
};

// ──────────────── SKIP LINK ────────────────
const SkipLink = () => (
  <a href="#main" className="skip-link">Saltar al contenido</a>
);

// ──────────────── NAV ────────────────
// currentPage: 'home' | 'portfolio' | 'services' | 'studio' | 'journal' | otro
const NAV_LINKS = [
  { k: 'portfolio', label: 'Portfolio', href: 'portfolio.html' },
  { k: 'services',  label: 'Servicios', href: 'services.html' },
  { k: 'studio',    label: 'Estudio',   href: 'studio.html' },
  { k: 'journal',   label: 'Diario',    href: 'journal.html' },
];

const Nav = ({ currentPage = 'home' }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const burgerRef = React.useRef(null);
  const contactHref = currentPage === 'home' ? '#contact' : 'index.html#contact';

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Cerrar con Escape y bloquear scroll del body mientras está abierto
  React.useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') { setMenuOpen(false); burgerRef.current && burgerRef.current.focus(); } };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [menuOpen]);

  return (
    <header className={`hp-nav ${scrolled ? 'hp-nav--scrolled' : ''} ${menuOpen ? 'hp-nav--open' : ''}`}>
      <a href="index.html" className="hp-nav__brand" aria-label={`${SITE.name}, inicio`}>
        <GarabatoLogo size={30}/>
      </a>
      <nav aria-label="Principal" className="hp-nav__primary">
        <ul className="hp-nav__links">
          {NAV_LINKS.map(l => (
            <li key={l.k}>
              <a href={l.href} className={currentPage === l.k ? 'is-active' : ''} aria-current={currentPage === l.k ? 'page' : undefined}>{l.label}</a>
            </li>
          ))}
        </ul>
      </nav>
      <div className="hp-nav__cta">
        <a href={contactHref} className="btn btn--primary btn--sm">
          Empezar un proyecto <Icon name="arrow-right" size={14}/>
        </a>
      </div>
      <button
        ref={burgerRef}
        type="button"
        className="hp-nav__burger"
        aria-label={menuOpen ? 'Cerrar menú' : 'Abrir menú'}
        aria-expanded={menuOpen}
        aria-controls="mobile-menu"
        onClick={() => setMenuOpen(v => !v)}
      >
        <Icon name={menuOpen ? 'close' : 'menu'} size={22}/>
      </button>
      {menuOpen && (
        <nav id="mobile-menu" className="hp-nav__mobile" aria-label="Menú móvil">
          {NAV_LINKS.map(l => (
            <a key={l.k} href={l.href} className={currentPage === l.k ? 'is-active' : ''} aria-current={currentPage === l.k ? 'page' : undefined} onClick={() => setMenuOpen(false)}>{l.label}</a>
          ))}
          <a href={contactHref} className="btn btn--lg btn--primary" onClick={() => setMenuOpen(false)}>
            Empezar un proyecto
          </a>
        </nav>
      )}
    </header>
  );
};

// ──────────────── FOOTER ────────────────
const Footer = () => {
  const cols = [
    { h: 'Estudio',  items: [['Sobre nosotros', 'studio.html'], ['Equipo', 'studio.html#team'], ['Historia', 'studio.html#history'], ['Manifiesto', 'studio.html#manifesto']] },
    { h: 'Trabajo',  items: [['Portfolio', 'portfolio.html'], ['Servicios', 'services.html'], ['Proceso', 'services.html#process'], ['Contacto', 'index.html#contact']] },
    { h: 'Recursos', items: [['Diario', 'journal.html'], ['Design System', 'Design System.html'], ['Privacidad', 'legal.html#privacidad'], ['Términos', 'legal.html#terminos']] },
    { h: 'Contacto', items: [[SITE.email, `mailto:${SITE.email}`], [SITE.phone, SITE.phoneHref], [SITE.address, null], [`${SITE.neighborhood}, ${SITE.city}`, null]] },
  ];
  return (
    <footer className="hp-footer">
      <div className="hp-footer__huge" aria-hidden="true">
        <SquiggleScatter items={[
          { variant: 'curl', color: 'yellow',  size: 'lg', top: '30%', left: '4%',  rotate: -8, float: true },
          { variant: 'ring', color: 'magenta', size: 'md', top: '15%', right: '10%', rotate: 15, float: true },
          { variant: 'hook', color: 'violet',  size: 'md', bottom: '25%', left: '46%', rotate: -10 },
          { variant: 'dash', color: 'orange',  size: 'sm', bottom: '30%', right: '22%', rotate: 0 },
        ]}/>
        <svg className="hp-footer__wordmark" viewBox="0 0 800 180" preserveAspectRatio="xMidYMid meet" focusable="false">
          <text x="400" y="150" textAnchor="middle">Garabato.</text>
        </svg>
      </div>
      <div className="hp-footer__inner">
        <div className="hp-footer__brand">
          <GarabatoLogo size={30} inverse/>
          <p className="t-body" style={{ color: '#C9C9D1', marginTop: 20, maxWidth: 340 }}>
            {SITE.tagline}.<br/>
            {SITE.city}, {SITE.country}.
          </p>
          <div className="hp-footer__social">
            {SITE.social.map(s => (<a key={s.label} href={s.href} target="_blank" rel="noopener noreferrer">{s.label}</a>))}
          </div>
        </div>
        <div className="hp-footer__cols">
          {cols.map(c => (
            <div key={c.h}>
              <div className="t-eyebrow" style={{ color: 'var(--brand-yellow)' }}>{c.h}</div>
              <ul>
                {c.items.map(([label, href], i) => (
                  <li key={i}>{href ? <a href={href}>{label}</a> : <span>{label}</span>}</li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      </div>
      <div className="hp-footer__bottom">
        <div className="t-caption" style={{ color: '#9A9AA6' }}>
          © {new Date().getFullYear()} {SITE.legalName} · Todos los garabatos reservados · NIT {SITE.nit}
        </div>
        <div style={{ display: 'flex', gap: 20 }}>
          <a href="legal.html#privacidad" className="t-caption" style={{ color: '#C9C9D1' }}>Política de privacidad</a>
          <a href="legal.html#terminos" className="t-caption" style={{ color: '#C9C9D1' }}>Términos</a>
        </div>
      </div>
    </footer>
  );
};

// ──────────────── PAGE HEADER (inner pages) ────────────────
const PageHeader = ({ eyebrow, title, subtitle, bg = 'paper', squiggles = [], children }) => {
  const dark = bg === 'magenta' || bg === 'violet' || bg === 'ink' || (typeof bg === 'string' && bg.startsWith('#') && bg !== '#FFD000' && bg !== '#FF9800');
  const custom = typeof bg === 'string' && bg.startsWith('#');
  return (
    <section className={`hp-page-header ${custom ? '' : `hp-page-header--${bg}`}`} style={custom ? { background: bg } : undefined}>
      <SquiggleScatter items={squiggles}/>
      <div className="hp-page-header__inner">
        <div className="t-eyebrow" style={{ color: dark ? 'var(--brand-yellow)' : 'var(--brand-magenta)' }}>{eyebrow}</div>
        <h1 className="t-display-xl" style={{ marginTop: 24, color: dark ? '#fff' : 'var(--ink-900)' }}>
          {title}
        </h1>
        {subtitle && (
          <p className="t-body-lg" style={{ color: dark ? 'rgba(255,255,255,0.84)' : 'var(--fg-muted)', marginTop: 24, maxWidth: 720 }}>{subtitle}</p>
        )}
        {children}
      </div>
    </section>
  );
};

// ──────────────── CONTACT FORM ────────────────
// Envía a SITE.formEndpoint (JSON, compatible con Formspree/Netlify
// functions). Si no hay endpoint configurado, cae a un mailto: con
// el mensaje prellenado para que igual llegue.
const BUDGETS = ['< USD 15k', 'USD 15–40k', 'USD 40–100k', '+ USD 100k', 'No sé todavía'];
const PROJECT_TYPES = ['Identidad / Branding', 'Diseño de producto', 'Motion / Video', 'Editorial', 'Otro / Mixto'];

const ContactForm = () => {
  const [status, setStatus] = React.useState('idle'); // idle | sending | sent | mailto | error
  const [errors, setErrors] = React.useState({});
  const uid = React.useId ? React.useId() : 'cf';
  const id = (k) => `${uid}-${k}`;

  const validate = (data) => {
    const e = {};
    if (!data.name.trim()) e.name = 'Contanos cómo te llamás.';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) e.email = 'Necesitamos un email válido para responderte.';
    if (!data.type) e.type = 'Elegí el tipo de proyecto.';
    if (data.message.trim().length < 20) e.message = 'Un par de líneas más nos ayudan a entender el proyecto.';
    return e;
  };

  const onSubmit = async (ev) => {
    ev.preventDefault();
    const fd = new FormData(ev.currentTarget);
    const data = Object.fromEntries(fd.entries());
    const e = validate(data);
    setErrors(e);
    if (Object.keys(e).length) {
      const first = ev.currentTarget.querySelector('[aria-invalid="true"]');
      first && first.focus();
      return;
    }
    if (data.website) return; // honeypot
    if (!SITE.formEndpoint) {
      const subject = encodeURIComponent(`Proyecto: ${data.type} — ${data.name}`);
      const body = encodeURIComponent(
        `Nombre: ${data.name}\nEmail: ${data.email}\nEmpresa: ${data.company || '-'}\nTipo: ${data.type}\nPresupuesto: ${data.budget}\n\n${data.message}`
      );
      window.location.href = `mailto:${SITE.email}?subject=${subject}&body=${body}`;
      setStatus('mailto');
      return;
    }
    setStatus('sending');
    try {
      const res = await fetch(SITE.formEndpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({ ...data, _subject: `Proyecto: ${data.type} — ${data.name}` }),
      });
      const json = await res.json().catch(() => ({}));
      if (res.status === 400 && json.errors) { setErrors(json.errors); setStatus('idle'); return; }
      if (!res.ok || json.ok === false) throw new Error(json.error || `HTTP ${res.status}`);
      setStatus('sent');
    } catch (err) {
      console.error('[contact]', err);
      setStatus('error');
    }
  };

  if (status === 'sent' || status === 'mailto') {
    return (
      <div className="hp-contact__form" role="status" aria-live="polite">
        <div className="hp-contact__sent">
          <Icon name="check" size={32} color="var(--brand-yellow)"/>
          <div className="t-h2" style={{ color: '#fff', marginTop: 16 }}>
            {status === 'sent' ? 'Recibimos tu mensaje.' : 'Se abrió tu correo con el mensaje listo.'}
          </div>
          <p className="t-body" style={{ color: 'rgba(255,255,255,0.84)', marginTop: 12 }}>
            {status === 'sent'
              ? 'Te escribimos en las próximas 24 horas hábiles.'
              : <>Si no se abrió, escribinos directo a <a href={`mailto:${SITE.email}`} style={{ color: 'var(--brand-yellow)' }}>{SITE.email}</a>.</>}
            {' '}Mientras tanto, podés ver algunos <a href="portfolio.html" style={{ color: 'var(--brand-yellow)' }}>proyectos recientes</a>.
          </p>
        </div>
      </div>
    );
  }

  const Err = ({ k }) => errors[k] ? <div id={id(`${k}-err`)} className="field__error hp-contact__error" role="alert">{errors[k]}</div> : null;
  const inputProps = (k) => ({
    id: id(k), name: k,
    'aria-invalid': errors[k] ? 'true' : undefined,
    'aria-describedby': errors[k] ? id(`${k}-err`) : undefined,
  });

  return (
    <form className="hp-contact__form" onSubmit={onSubmit} noValidate>
      <div className="field">
        <label className="field__label" htmlFor={id('name')}>Nombre</label>
        <input className="input" placeholder="Tu nombre" autoComplete="name" required {...inputProps('name')}/>
        <Err k="name"/>
      </div>
      <div className="field">
        <label className="field__label" htmlFor={id('email')}>Email</label>
        <input type="email" className="input" placeholder="vos@trabajo.com" autoComplete="email" required {...inputProps('email')}/>
        <Err k="email"/>
      </div>
      <div className="field">
        <label className="field__label" htmlFor={id('company')}>Empresa <span className="field__optional">(opcional)</span></label>
        <input className="input" placeholder="Dónde trabajás" autoComplete="organization" {...inputProps('company')}/>
      </div>
      <div className="field">
        <label className="field__label" htmlFor={id('type')}>Tipo de proyecto</label>
        <select className="input select" defaultValue="" required {...inputProps('type')}>
          <option value="" disabled>Elegir…</option>
          {PROJECT_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
        </select>
        <Err k="type"/>
      </div>
      <div className="field" style={{ gridColumn: '1 / -1' }}>
        <label className="field__label" htmlFor={id('message')}>Contanos de tu proyecto</label>
        <textarea className="input textarea" placeholder="Un par de líneas sobre contexto, urgencia, lo que ya probaste…" required {...inputProps('message')}/>
        <Err k="message"/>
      </div>
      <fieldset className="field hp-contact__fieldset" style={{ gridColumn: '1 / -1' }}>
        <legend className="field__label">Presupuesto estimado</legend>
        <div className="hp-contact__budget">
          {BUDGETS.map((b, i) => (
            <label key={b} className="hp-contact__budget-item">
              <input type="radio" name="budget" value={b} defaultChecked={i === 1}/>
              <span>{b}</span>
            </label>
          ))}
        </div>
      </fieldset>
      {/* honeypot anti-spam */}
      <div className="hp-contact__hp" aria-hidden="true">
        <label htmlFor={id('website')}>Sitio web</label>
        <input id={id('website')} name="website" tabIndex={-1} autoComplete="off"/>
      </div>
      <div style={{ gridColumn: '1 / -1', display: 'flex', gap: 16, alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', marginTop: 8 }}>
        <div className="t-caption" style={{ color: 'rgba(255,255,255,0.84)' }} aria-live="polite">
          {status === 'error'
            ? <span role="alert">No pudimos enviar el mensaje. Probá de nuevo o escribinos a <a href={`mailto:${SITE.email}`} style={{ color: 'var(--brand-yellow)' }}>{SITE.email}</a>.</span>
            : 'Respondemos en 24h hábiles. Sin newsletter disfrazado.'}
        </div>
        <button type="submit" className="btn btn--xl btn--yellow" disabled={status === 'sending'}>
          {status === 'sending' ? 'Enviando…' : 'Enviar'} <Icon name="arrow-right" size={18}/>
        </button>
      </div>
    </form>
  );
};

Object.assign(window, { Preloader, SkipLink, Nav, Footer, PageHeader, ContactForm, NAV_LINKS });

// ──────────────── TWEAKS PANEL ────────────────
// Panel in-page que aparece con el toggle "Tweaks" del toolbar del
// host de preview. Controla intensidad de efectos, grano y
// movimiento en vivo. Fuera de un iframe no hace nada visible.
const Tweaks = ({ defaults = {} }) => {
  const init = { speed: 6, grain: 5, motion: true, ...defaults };
  const [open, setOpen] = React.useState(false);
  const [v, setV] = React.useState(init);
  const embedded = window.parent && window.parent !== window;
  const post = (msg) => { if (embedded) window.parent.postMessage(msg, '*'); };

  // aplicar a CSS vars + clases
  React.useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty('--fx-speed', (1.4 - v.speed * 0.08).toFixed(2));
    root.style.setProperty('--fx-grain', (v.grain * 0.012).toFixed(3));
    document.body.classList.toggle('fx-no-motion', !v.motion);
  }, [v]);

  // protocolo host: listener ANTES de anunciar disponibilidad
  React.useEffect(() => {
    if (!embedded) return;
    const onMsg = (e) => {
      const t = e.data && e.data.type;
      if (t === '__activate_edit_mode') setOpen(true);
      else if (t === '__deactivate_edit_mode') setOpen(false);
    };
    window.addEventListener('message', onMsg);
    post({ type: '__edit_mode_available' });
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const set = (key, val) => {
    setV((s) => ({ ...s, [key]: val }));
    post({ type: '__edit_mode_set_keys', edits: { [key]: val } });
  };
  const close = () => { setOpen(false); post({ type: '__edit_mode_dismissed' }); };

  if (!open) return null;
  return (
    <div className="tweaks">
      <div className="tweaks__head">
        <span className="t-label">Tweaks</span>
        <button className="tweaks__x" onClick={close} aria-label="Cerrar"><Icon name="close" size={16}/></button>
      </div>
      <label className="tweaks__row">
        <span>Intensidad de efectos</span>
        <input type="range" min="0" max="10" step="1" value={v.speed}
          onChange={(e) => set('speed', +e.target.value)}/>
        <em>{v.speed}</em>
      </label>
      <label className="tweaks__row">
        <span>Grano / textura</span>
        <input type="range" min="0" max="10" step="1" value={v.grain}
          onChange={(e) => set('grain', +e.target.value)}/>
        <em>{v.grain}</em>
      </label>
      <label className="tweaks__row tweaks__row--toggle">
        <span>Movimiento</span>
        <button
          className={`tweaks__switch ${v.motion ? 'is-on' : ''}`}
          onClick={() => set('motion', !v.motion)}
          aria-pressed={v.motion}
        ><i/></button>
      </label>
    </div>
  );
};

Object.assign(window, { Tweaks });
