/* global React, PhotoBlock, Marquee, CursorBubble, VS_DATA */
const { useState: usePageState, useMemo: usePageMemo, useRef: usePageRef, useEffect: usePageEffect } = React;

// ─────────────────────────────────────────────────────────────────────────────
// HOME
// ─────────────────────────────────────────────────────────────────────────────
function HomePage({ t, lang, setRoute }) {
  const photos = VS_DATA.photos;
  const featured = photos.filter(p => p.feat).slice(0, 6);
  const heroPhoto = featured[0];

  return (
    <>
      <section className="hero">
        <div className="hero-grid">
          <div className="hero-text">
            <div className="eyebrow">
              <span className="eyebrow-rule" />
              <em>{t.hero.eyebrow}</em>
            </div>

            <h1 className="display display-hero">
              <span className="display-line">{t.hero.line1}</span>
              <span className="display-line">
                {t.hero.line2_a}<em>{t.hero.line2_em}</em>{t.hero.line2_b}
              </span>
            </h1>

            <p className="hero-sub">{t.hero.sub}</p>

            <div className="hero-actions">
              <button className="cta cta-fill" onClick={() => setRoute('portfolio')}>
                <span>{t.hero.cta}</span>
                <span className="cta-arrow" aria-hidden>→</span>
              </button>
              <button className="cta cta-ghost" onClick={() => setRoute('contact')}>
                {t.common.getInTouch}
              </button>
            </div>
          </div>

          <div className="hero-photo">
            <PhotoBlock photo={heroPhoto} lang={lang} ratio="3 / 4" priority />
            <div className="hero-photo-meta">
              <span className="mono">{heroPhoto.id}</span>
              <span className="mono">{cat(heroPhoto.cat, t)}</span>
            </div>
          </div>
        </div>

        <div className="hero-marquee" aria-hidden="false">
          <Marquee dur={55}>
            {[
              t.featured.title_em, '★',
              t.hero.line1, '★',
              t.featured.eyebrow, '★',
              t.aboutTeaser.line, '★',
            ].map((x, i) => (
              <span key={i} className="marquee-item">{x}</span>
            ))}
          </Marquee>
        </div>
      </section>

      <section className="section">
        <div className="section-head">
          <div className="eyebrow"><em>{t.featured.eyebrow}</em></div>
          <h2 className="display display-mid">
            {t.featured.title_a} <em>{t.featured.title_em}</em> {t.featured.title_b}
          </h2>
        </div>

        <div className="featured-grid">
          {featured.slice(1, 5).map((p, i) => (
            <a key={p.id}
               className={'featured-card featured-card-' + i}
               onClick={() => setRoute('portfolio')}>
              <PhotoBlock photo={p} lang={lang}
                          ratio={i === 0 ? '4 / 5' : i === 1 ? '1 / 1' : i === 2 ? '5 / 6' : '4 / 5'} />
            </a>
          ))}
        </div>

        <div className="section-foot">
          <button className="link-arrow" onClick={() => setRoute('portfolio')}>
            <span>{t.common.viewAll}</span><span aria-hidden>→</span>
          </button>
        </div>
      </section>

      <section className="section about-teaser">
        <div className="about-teaser-grid">
          <div className="eyebrow"><em>{t.aboutTeaser.eyebrow}</em></div>
          <p className="about-teaser-line">
            {t.aboutTeaser.line}
          </p>
          <button className="link-arrow" onClick={() => setRoute('about')}>
            <span>{t.aboutTeaser.more}</span><span aria-hidden>→</span>
          </button>
        </div>
      </section>

      <section className="section cta-band">
        <h3 className="display display-cta">
          {t.cta.line_a}<em>{t.cta.line_em}</em>
        </h3>
        <button className="cta cta-fill cta-large" onClick={() => setRoute('contact')}>
          <span>{t.cta.send}</span>
          <span className="cta-arrow" aria-hidden>→</span>
        </button>
      </section>
    </>
  );
}

function cat(c, t) {
  return ({ restaurant: t.portfolio.restaurant, brand: t.portfolio.brand,
            social: t.portfolio.social, onlocation: t.portfolio.onlocation }[c] || c);
}

// ─────────────────────────────────────────────────────────────────────────────
// PORTFOLIO — grid variant tweakable: masonry / strict / cinematic
// ─────────────────────────────────────────────────────────────────────────────
function PortfolioPage({ t, lang, gridVariant }) {
  const [filter, setFilter] = usePageState('all');
  const items = VS_DATA.photos.filter(p => filter === 'all' || p.cat === filter);
  const containerRef = usePageRef(null);

  const cats = [
    { id: 'all',         label: t.portfolio.all },
    { id: 'restaurant',  label: t.portfolio.restaurant },
    { id: 'brand',       label: t.portfolio.brand },
    { id: 'social',      label: t.portfolio.social },
    { id: 'onlocation',  label: t.portfolio.onlocation },
  ];

  return (
    <>
      <section className="page-head">
        <div className="eyebrow"><em>{t.nav.portfolio}</em></div>
        <h1 className="display display-page">
          {t.portfolio.title_a} <em>{t.portfolio.title_em}</em>{t.portfolio.title_b}
        </h1>
        <p className="page-sub">{t.portfolio.sub}</p>
      </section>

      <section className="filters">
        <div className="filters-row">
          {cats.map(c => (
            <button key={c.id}
                    className={'filter-btn' + (filter === c.id ? ' is-active' : '')}
                    onClick={() => setFilter(c.id)}>
              <span>{c.label}</span>
              <span className="filter-count mono">
                {c.id === 'all' ? VS_DATA.photos.length : VS_DATA.photos.filter(p => p.cat === c.id).length}
              </span>
            </button>
          ))}
        </div>
        <div className="filters-meta mono">
          {String(items.length).padStart(2, '0')} / {String(VS_DATA.photos.length).padStart(2, '0')}
        </div>
      </section>

      <section className={'pf pf-' + gridVariant} ref={containerRef}>
        <CursorBubble targetRef={containerRef} label="VIEW" />
        {items.length === 0 ? (
          <div className="pf-empty">{t.portfolio.empty}</div>
        ) : (
          items.map((p, i) => (
            <a key={p.id} className="pf-item" data-i={i % 12}>
              <PhotoBlock photo={p} lang={lang} ratio={ratioFor(i, gridVariant)} />
              <div className="pf-meta">
                <span className="mono">{p.id}</span>
                <span className="mono">{cat(p.cat, t)}</span>
              </div>
            </a>
          ))
        )}
      </section>
    </>
  );
}

function ratioFor(i, variant) {
  if (variant === 'strict') return '4 / 5';
  if (variant === 'cinematic') return i % 4 === 0 ? '3 / 4' : '4 / 3';
  // masonry: rotate through ratios deterministically
  const ratios = ['4 / 5', '1 / 1', '5 / 6', '4 / 5', '3 / 4', '4 / 5', '1 / 1', '5 / 7', '4 / 5', '3 / 4', '1 / 1', '4 / 5'];
  return ratios[i % ratios.length];
}

// ─────────────────────────────────────────────────────────────────────────────
// ABOUT
// ─────────────────────────────────────────────────────────────────────────────
function AboutPage({ t, lang }) {
  const aboutPhoto = VS_DATA.photos[20]; // bakery 5am
  const sidePhoto = VS_DATA.photos[5];   // olive oil

  return (
    <>
      <section className="page-head">
        <div className="eyebrow"><em>{t.about.eyebrow}</em></div>
        <h1 className="display display-page">
          {t.about.title_a}<em>{t.about.title_em}</em> {t.about.title_b}
        </h1>
      </section>

      <section className="about-body">
        <div className="about-portrait">
          <PhotoBlock photo={aboutPhoto} lang={lang} ratio="3 / 4" />
        </div>
        <div className="about-text">
          <p className="lead">{t.about.bio_p1}</p>
          <p>{t.about.bio_p2}</p>
          <p className="quiet">{t.about.bio_p3}</p>
        </div>
      </section>

      <section className="stats">
        <div className="stat">
          <div className="stat-num">{VS_DATA.stats.years}</div>
          <div className="stat-lbl"><em>{t.about.statsLabel.years}</em></div>
        </div>
        <div className="stat">
          <div className="stat-num">{VS_DATA.stats.clients}+</div>
          <div className="stat-lbl"><em>{t.about.statsLabel.clients}</em></div>
        </div>
        <div className="stat">
          <div className="stat-num">{VS_DATA.stats.dishes.toLocaleString(lang === 'ru' ? 'ru-RU' : lang === 'he' ? 'he-IL' : 'en-US')}</div>
          <div className="stat-lbl"><em>{t.about.statsLabel.dishes}</em></div>
        </div>
        <div className="stat about-side-photo">
          <PhotoBlock photo={sidePhoto} lang={lang} ratio="1 / 1" />
        </div>
      </section>
    </>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// SERVICES
// ─────────────────────────────────────────────────────────────────────────────
function ServicesPage({ t, setRoute }) {
  return (
    <>
      <section className="page-head">
        <div className="eyebrow"><em>{t.services.eyebrow}</em></div>
        <h1 className="display display-page">
          {t.services.title_a} <em>{t.services.title_em}</em> {t.services.title_b}
        </h1>
      </section>

      <section className="services-grid">
        {t.services.items.map(s => (
          <article key={s.n} className="svc">
            <div className="svc-num mono">{s.n}</div>
            <h3 className="svc-title">{s.t}</h3>
            <p className="svc-desc">{s.d}</p>
          </article>
        ))}
      </section>

      <section className="section cta-band">
        <button className="cta cta-fill cta-large" onClick={() => setRoute('contact')}>
          <span>{t.services.ask}</span>
          <span className="cta-arrow" aria-hidden>→</span>
        </button>
      </section>
    </>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// CONTACT — fake Cloudflare Turnstile widget, validation, optimistic submit
// ─────────────────────────────────────────────────────────────────────────────
function ContactPage({ t, lang }) {
  const [form, setForm] = usePageState({ name: '', email: '', brand: '', message: '' });
  const [errs, setErrs] = usePageState({});
  const [verified, setVerified] = usePageState(false);
  const [verifying, setVerifying] = usePageState(false);
  const [state, setState] = usePageState('idle'); // idle | sending | sent

  function update(k, v) {
    setForm(f => ({ ...f, [k]: v }));
    if (errs[k]) setErrs(e => ({ ...e, [k]: null }));
  }

  function startVerify() {
    if (verified || verifying) return;
    setVerifying(true);
    setTimeout(() => { setVerifying(false); setVerified(true); }, 1200);
  }

  function submit(e) {
    e.preventDefault();
    const next = {};
    if (!form.name.trim()) next.name = '!';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) next.email = '!';
    if (!form.message.trim() || form.message.trim().length < 10) next.message = '!';
    if (!verified) next.verify = '!';
    setErrs(next);
    if (Object.keys(next).length) return;
    setState('sending');
    setTimeout(() => setState('sent'), 1200);
  }

  function reset() {
    setForm({ name: '', email: '', brand: '', message: '' });
    setVerified(false);
    setState('idle');
  }

  return (
    <>
      <section className="page-head">
        <div className="eyebrow"><em>{t.contact.eyebrow}</em></div>
        <h1 className="display display-page">
          {t.contact.title_a} <em>{t.contact.title_em}</em>
        </h1>
        <p className="page-sub">{t.contact.sub}</p>
      </section>

      <section className="contact-body">
        <form className="contact-form" onSubmit={submit} noValidate>
          {state === 'sent' ? (
            <div className="form-success">
              <div className="form-success-mark">✓</div>
              <h3 className="display display-mid"><em>{t.contact.sent_a}</em></h3>
              <p>{t.contact.sent_b}</p>
              <button type="button" className="link-arrow" onClick={reset}>
                <span>{t.contact.sent_reset}</span><span aria-hidden>→</span>
              </button>
            </div>
          ) : (
            <>
              <Field label={t.contact.name} k="name" v={form.name} err={errs.name} update={update} />
              <Field label={t.contact.email} k="email" v={form.email} err={errs.email} update={update} type="email" />
              <Field label={t.contact.brand} k="brand" v={form.brand} update={update} optional />
              <Field label={t.contact.message} k="message" v={form.message} err={errs.message} update={update} ta />

              <div className={'turnstile' + (verified ? ' is-verified' : '') + (errs.verify ? ' is-err' : '')}>
                <button type="button" className="turnstile-check" onClick={startVerify} aria-pressed={verified}>
                  <span className={'turnstile-box' + (verifying ? ' is-spinning' : '')}>
                    {verified ? '✓' : verifying ? '' : ''}
                  </span>
                  <span className="turnstile-label">{verified ? t.contact.verified : t.contact.verify}</span>
                </button>
                <span className="turnstile-brand mono">CLOUDFLARE · TURNSTILE</span>
              </div>

              <button type="submit" className="cta cta-fill cta-large" disabled={state === 'sending'}>
                <span>{state === 'sending' ? t.contact.sending : t.contact.send}</span>
                <span className="cta-arrow" aria-hidden>→</span>
              </button>

              <p className="form-spam mono">{t.contact.spamNotice}</p>
            </>
          )}
        </form>

        <aside className="contact-direct">
          <div className="eyebrow"><em>{t.contact.direct}</em></div>
          <a className="contact-line" href={`mailto:${t.contact.email_addr}`}>{t.contact.email_addr}</a>
          <a className="contact-line" href={`tel:${t.contact.phone.replace(/\s/g,'')}`}>{t.contact.phone}</a>
          <div className="contact-line contact-line-quiet">{t.contact.social}</div>

          <div className="contact-rule" />

          <div className="contact-loc">
            <div className="mono eyebrow-mono">TEL AVIV · ISRAEL</div>
            <div className="contact-coords mono">32.0853° N · 34.7818° E</div>
          </div>
        </aside>
      </section>
    </>
  );
}

function Field({ label, k, v, err, update, type = 'text', ta = false, optional = false }) {
  const id = 'f-' + k;
  return (
    <label className={'field' + (err ? ' has-err' : '')} htmlFor={id}>
      <span className="field-label">
        {label}
        {optional && <span className="field-opt"> ·  </span>}
      </span>
      {ta ? (
        <textarea id={id} value={v} rows={5} onChange={e => update(k, e.target.value)} />
      ) : (
        <input id={id} type={type} value={v} onChange={e => update(k, e.target.value)} />
      )}
    </label>
  );
}

Object.assign(window, { HomePage, PortfolioPage, AboutPage, ServicesPage, ContactPage });
