// FashionFactoryDirect — pages

const GHL_WEBHOOK = 'https://services.leadconnectorhq.com/hooks/8xK1bIUUTCfbEt1syLby/webhook-trigger/c23498f0-0bb8-4e5b-8bb6-5d1b267ff679';

async function submitToGHL(payload) {
  try {
    const res = await fetch(GHL_WEBHOOK, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ...payload,
        submittedAt: new Date().toISOString(),
        pageUrl: typeof location !== 'undefined' ? location.href : '',
      }),
    });
    return res.ok;
  } catch (err) {
    console.error('GHL submit failed', err);
    return false;
  }
}

// Read a <form> into a plain object, collapsing single-value keys but
// preserving arrays for repeated names (checkbox groups).
function formToObject(form) {
  const fd = new FormData(form);
  const out = {};
  for (const key of new Set(fd.keys())) {
    const values = fd.getAll(key);
    out[key] = values.length > 1 ? values : values[0];
  }
  return out;
}

// Reusable checkbox-group control matching the editorial form aesthetic.
const CheckboxGroup = ({ name, label, hint, options, error }) => (
  <div className="form-row form-checkgroup">
    <label>{label} {hint && <span className="hint">{hint}</span>}</label>
    <div className="checkgroup-list">
      {options.map(opt => (
        <label key={opt} className="checkgroup-item">
          <input type="checkbox" name={name} value={opt} />
          <span className="box" aria-hidden="true">
            <svg viewBox="0 0 12 12"><path d="M2.5 6.5 L5 9 L9.5 3.5" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>
          </span>
          <span className="label">{opt}</span>
        </label>
      ))}
    </div>
    {error && <div className="form-inline-error">{error}</div>}
  </div>
);

// Editorial radio-card group — for the "I am a..." selector.
const RadioGroup = ({ name, label, options, value, onChange }) => (
  <div className="form-row form-radiogroup">
    <label>{label}</label>
    <div className="radiogroup-list">
      {options.map(opt => (
        <label key={opt} className={`radiogroup-item ${value === opt ? 'is-selected' : ''}`}>
          <input
            type="radio"
            name={name}
            value={opt}
            checked={value === opt}
            onChange={(e) => onChange && onChange(e.target.value)}
            required
          />
          <span className="dot" aria-hidden="true"><span /></span>
          <span className="label">{opt}</span>
        </label>
      ))}
    </div>
  </div>
);

// Single-checkbox consent control — matches editorial style.
const ConsentCheckbox = ({ name, label }) => (
  <label className="form-consent">
    <input type="checkbox" name={name} value="yes" />
    <span className="box" aria-hidden="true">
      <svg viewBox="0 0 12 12"><path d="M2.5 6.5 L5 9 L9.5 3.5" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>
    </span>
    <span className="label">{label}</span>
  </label>
);

// Editorial thank-you screen rendered in place of the submitted form
const ThanksView = ({ thanks, dark }) => (
  <div className={`form-thanks ${dark ? 'dark' : ''}`}>
    <div className="form-thanks-inner">
      <div className="form-thanks-mark" aria-hidden="true">
        <svg viewBox="0 0 56 56" width="56" height="56">
          <circle cx="28" cy="28" r="27" fill="none" stroke="currentColor" strokeWidth="0.5" opacity="0.35" />
          <path d="M17 28.5 L25 36.5 L40 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </div>
      <div className="eyebrow">{thanks.eyebrow}</div>
      <h3 className="display-md">{richText(thanks.title)}</h3>
      <p className="lede">{thanks.body}</p>
    </div>
  </div>
);

const HomePage = ({ t, onNav, tweaks }) => (
  <main>
    <Hero variant={tweaks.heroVariant} t={t} videoSrc={tweaks.heroVideo} onNav={onNav} />
    <Marquee items={t.marquee} />

    <section className="section">
      <div className="wrap">
        <div className="section-head">
          <div>
            <div className="eyebrow" style={{marginBottom:16}}>{t.services.eyebrow}</div>
            <h2 className="display-lg">{richText(t.services.title)}</h2>
          </div>
          <p className="lede">{t.services.lede}</p>
        </div>
        <Services variant={tweaks.servicesVariant} items={t.services.items} onNav={onNav} />
      </div>
    </section>

    <StatsSection t={t} />

    <WarehousesSection t={t} />

    <ProcessSection t={t} />

    <DualCTASection t={t} onNav={onNav} />
  </main>
);

// ── Services page ────────────────────────────────────────
const ServicesPage = ({ t, onNav }) => (
  <main>
    <section className="about-hero">
      <div className="wrap">
        <div className="eyebrow" style={{marginBottom:24}}>{t.services_page.eyebrow}</div>
        <h1>{t.services_page.title}</h1>
        <p className="lede" style={{marginTop:32, maxWidth:'52ch'}}>{t.services_page.lede}</p>
      </div>
    </section>

    <section style={{paddingBottom:'clamp(72px, 10vw, 140px)'}}>
      <div className="wrap">
        <div style={{display:'flex', flexDirection:'column', gap:'clamp(64px, 8vw, 120px)'}}>
          {t.services_page.detail.map((s, i) => (
            <div key={s.num} className={`svc-edit-row ${i % 2 === 1 ? 'flip' : ''}`}>
              <div className="img-col" style={{backgroundImage:`url(${IMG_SLOTS['services_page_'+s.name] || ''})`, backgroundSize:'cover', backgroundPosition:'center'}} />
              <div className="txt-col">
                <div className="num">{s.num} — {s.name}</div>
                <h3>{s.title}</h3>
                <div className="tiny">{s.sub}</div>
                <p style={{margin:0, color:'var(--ink-2)', fontSize:16, lineHeight:1.65}}>{s.desc}</p>
                <ul style={{listStyle:'none', padding:0, margin:'16px 0 0', display:'flex', flexDirection:'column', gap:0}}>
                  {s.bullets.map((b, j) => (
                    <li key={j} style={{
                      padding:'14px 0', borderTop:'0.5px solid var(--line)',
                      display:'flex', gap:16, fontSize:14, color:'var(--ink-2)'
                    }}>
                      <span style={{fontFamily:'var(--f-display)', fontStyle:'italic', color:'var(--accent)', minWidth:28}}>
                        0{j+1}
                      </span>
                      <span>{b}</span>
                    </li>
                  ))}
                </ul>
                {s.link && (
                  <div style={{marginTop:24}}>
                    <button className="btn-link" onClick={() => onNav(s.link.page)}>{s.link.label} <span>→</span></button>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>

    <DualCTASection t={t} onNav={onNav} />
  </main>
);

// ── About page ───────────────────────────────────────────
const AboutPage = ({ t, onNav }) => (
  <main>
    <section className="about-hero">
      <div className="wrap">
        <div className="eyebrow" style={{marginBottom:24}}>{t.about.eyebrow}</div>
        <h1>{richText(t.about.title)}</h1>
        <p className="lede" style={{marginTop:32, maxWidth:'56ch'}}>{t.about.lede}</p>
      </div>
    </section>

    <section style={{paddingBottom:'clamp(56px, 8vw, 96px)'}}>
      <div className="wrap">
        <div className="about-image" style={{backgroundImage:`url(${IMG_SLOTS.about_image || ''})`, backgroundSize:'cover', backgroundPosition:'center'}} />
      </div>
    </section>

    <section className="section" style={{paddingTop:0}}>
      <div className="wrap">
        <div style={{display:'flex', flexDirection:'column', gap:'clamp(56px, 7vw, 96px)'}}>
          {t.about.sections.map(s => (
            <div key={s.heading} className="about-grid">
              <h3>{s.heading}</h3>
              <p>{s.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>

    <WarehousesSection t={t} />

    <DualCTASection t={t} onNav={onNav} />
  </main>
);

// ── Contact page ─────────────────────────────────────────
const ContactPage = ({ t, onNav }) => {
  const f = t.contact.form;
  const [status, setStatus] = React.useState('idle'); // idle | sending | sent | error
  const [type, setType] = React.useState('');
  const [servicesError, setServicesError] = React.useState('');

  const onSubmit = async (e) => {
    e.preventDefault();
    if (status === 'sending') return;
    const data = formToObject(e.target);
    if (!data.services || (Array.isArray(data.services) && data.services.length === 0)) {
      setServicesError(f.servicesError);
      return;
    }
    setServicesError('');
    data.source = 'contact-page';
    data.marketingConsent = data.marketingConsent === 'yes';
    setStatus('sending');
    const ok = await submitToGHL(data);
    setStatus(ok ? 'sent' : 'error');
  };

  return (
    <main>
      <section className="about-hero">
        <div className="wrap">
          <div className="eyebrow" style={{marginBottom:24}}>{t.contact.eyebrow}</div>
          <h1>{richText(t.contact.title)}</h1>
          <p className="lede" style={{marginTop:32, maxWidth:'52ch'}}>{t.contact.lede}</p>
        </div>
      </section>

      <section className="section" style={{paddingTop:0}}>
        <div className="wrap">
          <div className="contact-grid">
            {status === 'sent' ? (
              <ThanksView thanks={t.contact.thanks} />
            ) : (
              <form className="form" onSubmit={onSubmit}>
                <RadioGroup name="type" label={f.type} options={f.typeOpts} value={type} onChange={setType} />
                <div className="form-row row-2">
                  <div>
                    <label>{f.firstName}</label>
                    <input name="firstName" type="text" required />
                  </div>
                  <div>
                    <label>{f.lastName}</label>
                    <input name="lastName" type="text" required />
                  </div>
                </div>
                <div className="form-row row-2">
                  <div>
                    <label>{f.email}</label>
                    <input name="email" type="email" required />
                  </div>
                  <div>
                    <label>{f.phone}</label>
                    <input name="phone" type="tel" required />
                  </div>
                </div>
                <div className="form-row">
                  <label>{f.company}</label>
                  <input name="company" type="text" required />
                </div>
                <CheckboxGroup name="services" label={f.services} hint={f.servicesHint} options={f.servicesOpts} error={servicesError} />
                <div className="form-row">
                  <label>{f.message} <span className="hint">{f.messageOpt}</span></label>
                  <textarea name="message" />
                </div>
                <ConsentCheckbox name="marketingConsent" label={f.marketing} />
                {status === 'error' && (
                  <div className="form-error">{t.contact.error}</div>
                )}
                <div>
                  <button className="btn" type="submit" disabled={status === 'sending'}>
                    {status === 'sending' ? f.sending : (status === 'error' ? f.errorRetry : f.submit)}
                    {status !== 'sending' && <span className="arr">→</span>}
                  </button>
                </div>
              </form>
            )}

            <div className="contact-info">
              <div className="contact-block">
                <h4>{t.contact.email.label}</h4>
                <p style={{fontFamily:'var(--f-display)', fontSize:32, fontWeight:400, letterSpacing:'-0.01em'}}>
                  {t.contact.email.val}
                </p>
              </div>

              <div className="contact-block">
                <h4>{t.contact.offices}</h4>
                <div style={{display:'grid', gap:24, marginTop:8}}>
                  <div>
                    <p className="tiny" style={{marginBottom:4}}>{t.contact.atl.city}</p>
                    <p style={{fontFamily:'var(--f-display)', fontSize:24, margin:'4px 0', lineHeight:1.25}}>{t.contact.atl.addr}</p>
                    <p style={{fontFamily:'var(--f-display)', fontSize:20, margin:'4px 0'}}>{t.contact.atl.phone}</p>
                    <p className="small">{t.contact.atl.lede}</p>
                  </div>
                  <div>
                    <p className="tiny" style={{marginBottom:4}}>{t.contact.ist.city}</p>
                    {t.contact.ist.addr && (
                      <p style={{fontFamily:'var(--f-display)', fontSize:24, margin:'4px 0', lineHeight:1.25}}>{t.contact.ist.addr}</p>
                    )}
                    <p style={{fontFamily:'var(--f-display)', fontSize:20, margin:'4px 0'}}>{t.contact.ist.phone}</p>
                    <p className="small">{t.contact.ist.lede}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
};

// ── For Brands page ──────────────────────────────────────
const ForBrandsPage = ({ t, onNav }) => {
  const fb = t.forbrands;
  const f = fb.form;
  return (
    <main>
      <section className="fb-hero">
        <div className="fb-hero-inner">
          <div>
            <div className="eyebrow">{fb.eyebrow}</div>
            <h1>{richText(fb.title)}</h1>
            <div className="hero-cta">
              <button className="btn" onClick={() => {
                const el = document.getElementById('fb-form-section');
                if (el) el.scrollIntoView({behavior:'smooth', block:'start'});
              }}>{fb.primaryCta} <span className="arr">→</span></button>
              <button className="btn btn-ghost" onClick={() => {
                const el = document.getElementById('fb-process-section');
                if (el) el.scrollIntoView({behavior:'smooth', block:'start'});
              }}>{fb.secondaryCta}</button>
            </div>
          </div>
          <div>
            <p className="lede">{fb.lede}</p>
            <div className="joor-badge">
              <span className="tag">{fb.partnerBadge.tag}</span>
              <span className="brand">{fb.partnerBadge.brand}</span>
            </div>
          </div>
        </div>
      </section>

      <section className="section" style={{paddingBottom: 0}}>
        <div className="wrap">
          <div className="section-head">
            <div>
              <div className="eyebrow" style={{marginBottom:16}}>{fb.pillarsEyebrow}</div>
              <h2 className="display-lg">{richText(fb.pillarsTitle)}</h2>
            </div>
            <div />
          </div>
          <div className="fb-pillars">
            {fb.pillars.map(p => (
              <div key={p.num} className="fb-pillar">
                <div className="num">{p.num}</div>
                <div className="kicker">{p.kicker}</div>
                <h3>{p.title}</h3>
                <p>{p.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section id="fb-process-section" className="section">
        <div className="wrap">
          <div className="section-head">
            <div>
              <div className="eyebrow" style={{marginBottom:16}}>{fb.processEyebrow}</div>
              <h2 className="display-lg">{richText(fb.processTitle)}</h2>
            </div>
            <p className="lede">{fb.processLede}</p>
          </div>
          <div className="fb-timeline">
            {fb.process.map(s => (
              <div key={s.num} className="fb-step">
                <div className="meta">
                  <span className="num">{s.num}</span>
                  <span className="when">{s.when}</span>
                </div>
                <h3>{s.title}</h3>
                <p>{s.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section fb-founding">
        <div className="wrap">
          <div className="fb-founding-grid">
            <div>
              <div className="eyebrow" style={{marginBottom:20}}>{fb.foundingEyebrow}</div>
              <h2 className="display-lg">{richText(fb.foundingTitle)}</h2>
              <p className="lede" style={{marginTop:24, maxWidth:'42ch'}}>{fb.foundingLede}</p>
            </div>
            <ul>
              {fb.foundingPoints.map((p, i) => <li key={i}>{p}</li>)}
            </ul>
          </div>
        </div>
      </section>

      <section id="fb-form-section" className="section fb-form">
        <div className="wrap">
          <div className="section-head">
            <div>
              <div className="eyebrow" style={{marginBottom:16}}>{fb.formEyebrow}</div>
              <h2 className="display-lg">{richText(fb.formTitle)}</h2>
            </div>
            <p className="lede">{fb.formLede}</p>
          </div>
          <ForBrandsForm fb={fb} />
        </div>
      </section>
    </main>
  );
};

const ForBrandsForm = ({ fb }) => {
  const f = fb.form;
  const [status, setStatus] = React.useState('idle');
  const [servicesError, setServicesError] = React.useState('');

  const onSubmit = async (e) => {
    e.preventDefault();
    if (status === 'sending') return;
    const data = formToObject(e.target);
    if (!data.services || (Array.isArray(data.services) && data.services.length === 0)) {
      setServicesError(f.servicesError);
      return;
    }
    setServicesError('');
    data.source = 'for-brands-page';
    data.marketingConsent = data.marketingConsent === 'yes';
    setStatus('sending');
    const ok = await submitToGHL(data);
    setStatus(ok ? 'sent' : 'error');
  };

  if (status === 'sent') {
    return <ThanksView thanks={fb.thanks} dark />;
  }

  return (
    <form className="form" style={{maxWidth: 720}} onSubmit={onSubmit}>
      <div className="form-row row-2">
        <div>
          <label>{f.firstName}</label>
          <input name="firstName" type="text" required />
        </div>
        <div>
          <label>{f.lastName}</label>
          <input name="lastName" type="text" required />
        </div>
      </div>
      <div className="form-row row-2">
        <div>
          <label>{f.email}</label>
          <input name="email" type="email" required />
        </div>
        <div>
          <label>{f.role}</label>
          <input name="role" type="text" required />
        </div>
      </div>
      <div className="form-row">
        <label>{f.company}</label>
        <input name="company" type="text" required />
      </div>
      <div className="form-row">
        <label>{f.stage}</label>
        <select name="stage" required defaultValue="">
          <option value="" disabled>—</option>
          {f.stageOpts.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      </div>
      <CheckboxGroup name="services" label={f.services} hint={f.servicesHint} options={f.servicesOpts} error={servicesError} />
      <div className="form-row">
        <label>{f.brief} <span className="hint">{f.briefOpt}</span></label>
        <textarea name="brief" />
      </div>
      <ConsentCheckbox name="marketingConsent" label={f.marketing} />
      {status === 'error' && (
        <div className="form-error">{fb.error}</div>
      )}
      <div>
        <button className="btn" type="submit" disabled={status === 'sending'}>
          {status === 'sending' ? f.sending : (status === 'error' ? f.errorRetry : f.submit)}
          {status !== 'sending' && <span className="arr">→</span>}
        </button>
      </div>
    </form>
  );
};

// ── JOOR page ────────────────────────────────────────────
const JoorPage = ({ t, onNav }) => {
  const j = t.joor;
  return (
    <main>
      <section className="joor-hero">
        <div className="joor-hero-inner">
          <div>
            <div className="eyebrow">{j.eyebrow}</div>
            <h1>{richText(j.title)}</h1>
            <p className="lede" style={{marginTop:28, maxWidth:'52ch'}}>{j.lede}</p>
            <div className="hero-cta">
              <button className="btn" onClick={() => onNav('contact')}>{j.primaryCta} <span className="arr">→</span></button>
              <a className="btn btn-ghost" href="https://www.joor.com" target="_blank" rel="noopener noreferrer">{j.secondaryCta} <span className="arr">↗</span></a>
            </div>
          </div>
          <div>
            <div className="joor-stamp">
              <span className="tag">EXCLUSIVE PARTNER</span>
              <span className="word">JOOR</span>
              <span className="country">TÜRKİYE / TURKEY</span>
            </div>
          </div>
        </div>
      </section>

      <section className="joor-hero-strip">
        <image-slot id="joor-hero-strip" shape="rect" placeholder="Editorial fashion image — full-bleed (drop here)" src={IMG_SLOTS.joor_hero_strip}></image-slot>
      </section>

      <section className="section">
        <div className="wrap">
          <div className="joor-about-grid">
            <div>
              <div className="eyebrow" style={{marginBottom:16}}>{j.aboutEyebrow}</div>
              <h2 className="display-lg">{richText(j.aboutTitle)}</h2>
            </div>
            <div className="body">
              {j.aboutBody.map((p, i) => <p key={i}>{p}</p>)}
            </div>
          </div>
        </div>
      </section>

      <section className="section joor-retailers">
        <div className="wrap">
          <div className="section-head">
            <div>
              <div className="eyebrow" style={{marginBottom:16}}>{j.retailerWall.eyebrow}</div>
              <h2 className="display-lg">{richText(j.retailerWall.title)}</h2>
            </div>
            <p className="lede">{j.retailerWall.sub}</p>
          </div>
          <div className="retailer-wall">
            {[0, 3, 6, 9].map(start => (
              <div key={start} className="retailer-row">
                {j.retailerWall.names.slice(start, start + 3).map(name => (
                  <div key={name} className="retailer-name">
                    <span className="retailer-mark" />
                    <span>{name}</span>
                  </div>
                ))}
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section joor-metrics-section">
        <div className="wrap">
          <div className="section-head">
            <div>
              <div className="eyebrow" style={{marginBottom:16}}>{j.metricsEyebrow}</div>
              <h2 className="display-lg">{richText(j.metricsTitle)}</h2>
            </div>
            <p className="lede">{j.metricsSub}</p>
          </div>
          <div className="joor-metrics-grid">
            {j.metrics.map(m => (
              <div key={m.label} className="joor-metric">
                <div className="v">{m.value}</div>
                <div className="l">{m.label}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="wrap">
          <div className="section-head">
            <div>
              <div className="eyebrow" style={{marginBottom:16}}>{j.proofEyebrow}</div>
              <h2 className="display-lg">{richText(j.proofTitle)}</h2>
            </div>
            <p className="lede">{j.proofIntro}</p>
          </div>
          <div className="joor-proof">
            {j.proofPoints.map((p, i) => (
              <div className="joor-proof-item" key={i}>
                <div className="stat">{p.stat}</div>
                <p>{p.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section joor-speed">
        <div className="wrap">
          <div className="joor-speed-grid">
            <div>
              <div className="eyebrow" style={{marginBottom:16}}>{j.speedEyebrow}</div>
              <h2>{richText(j.speedTitle)}</h2>
            </div>
            <div className="body">
              <p>{j.speedBody}</p>
            </div>
          </div>
        </div>
      </section>

      <section className="section joor-role">
        <div className="wrap">
          <div className="section-head">
            <div>
              <div className="eyebrow" style={{marginBottom:16}}>{j.roleEyebrow}</div>
              <h2 className="display-lg">{richText(j.roleTitle)}</h2>
            </div>
            <p className="lede">{j.roleBody}</p>
          </div>
          <ul>
            {j.roleBullets.map((b, i) => <li key={i}><span>{b}</span></li>)}
          </ul>
        </div>
      </section>

      <section className="section joor-gallery">
        <div className="wrap">
          <div className="eyebrow" style={{marginBottom:32}}>{j.galleryEyebrow}</div>
          <div className="joor-gallery-grid">
            <image-slot id="joor-gallery-1" shape="rect" placeholder="Showroom / market week" src={IMG_SLOTS.joor_gallery_1}></image-slot>
            <image-slot id="joor-gallery-2" shape="rect" placeholder="Line sheet / sample" src={IMG_SLOTS.joor_gallery_2}></image-slot>
            <image-slot id="joor-gallery-3" shape="rect" placeholder="Buyer / trade show" src={IMG_SLOTS.joor_gallery_3}></image-slot>
          </div>
        </div>
      </section>

      <section className="section joor-cta">
        <div className="wrap">
          <div className="section-head">
            <div>
              <div className="eyebrow" style={{marginBottom:16}}>{j.ctaEyebrow}</div>
              <h2 className="display-lg">{richText(j.ctaTitle)}</h2>
            </div>
            <p className="lede">{j.ctaBody}</p>
          </div>
          <div className="hero-cta">
            <button className="btn" onClick={() => onNav('contact')}>{j.ctaPrimary} <span className="arr">→</span></button>
            <a className="btn btn-ghost" href="https://www.joor.com" target="_blank" rel="noopener noreferrer">{j.ctaSecondary} <span className="arr">↗</span></a>
          </div>
          <div className="joor-source" style={{marginTop:48, borderTopColor:'rgba(250,248,244,0.15)', color:'rgba(250,248,244,0.45)'}}>
            {j.sourceNote}
          </div>
        </div>
      </section>
    </main>
  );
};

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