﻿/* global React, Nav, Footer, setupReveals, pageBase */
const { useState: useStateP, useEffect: useEffectP, useMemo } = React;

// Email obfuscation — keeps the address out of plain-text HTML crawlers
const _em  = () => atob('aGVsbG9AanBhenBob3RvZ3JhcGh5LmNvbQ==');
const _eml = () => 'mailto:' + _em();

function PageHero({ eyebrow, title, sub, crumbs, mood = 'warm', images }) {
  const base = pageBase();
  const [current, setCurrent] = useStateP(0);

  useEffectP(() => {
    if (!images || images.length <= 1) return;
    const id = setInterval(() => setCurrent(c => (c + 1) % images.length), 5500);
    return () => clearInterval(id);
  }, [images]);

  return (
    <section className="page-hero" data-mood={mood}>
      <div className="hero-media">
        <div className="hero-grain"></div>
        {(images || []).map((img, i) => {
          const src = typeof img === 'string' ? img : img.src;
          const alt = typeof img === 'string' ? '' : (img.alt || '');
          const pos = typeof img === 'object' && img.objectPosition ? img.objectPosition : undefined;
          return <img key={src} className={'hero-slide' + (i === current ? ' active' : '')} src={src} alt={alt} loading={i === 0 ? 'eager' : 'lazy'} style={pos ? { objectPosition: pos } : undefined} />;
        })}
      </div>
      <div className="hero-inner">
        <nav className="crumbs">
          <a href={base + 'index.html'}>Home</a>
          <span>/</span>
          {(crumbs || []).map((c, i) => (
            <React.Fragment key={i}>
              {c.href ? <a href={c.href}>{c.label}</a> : <span>{c.label}</span>}
              {i < crumbs.length - 1 && <span>/</span>}
            </React.Fragment>
          ))}
        </nav>
        <div className="hero-eyebrow"><span className="bar"></span>{eyebrow}</div>
        <h1 dangerouslySetInnerHTML={{ __html: title }} />
        {sub && <p className="sub">{sub}</p>}
      </div>
    </section>
  );
}

function SplitBlock({ eyebrow, title, paragraphs, lead, reverse, photoVariant = 'a', photoTag, checklist, imageSrc, imageAlt = '' }) {
  return (
    <section>
      <div className="container">
        <div className={'split-block' + (reverse ? ' reverse' : '')}>
          <div className="copy reveal">
            {eyebrow && <span className="eyebrow">{eyebrow}</span>}
            {title && <h2 className="section-title">{title}</h2>}
            {lead && <p className="lead">{lead}</p>}
            {(paragraphs || []).map((p, i) => <p key={i}>{p}</p>)}
            {checklist && (
              <ul className="checklist">
                {checklist.map((c, i) => <li key={i}>{c}</li>)}
              </ul>
            )}
          </div>
          <div className="img reveal" style={{ transitionDelay: '120ms' }}>
            <div className={'ph variant-' + photoVariant}>
              {imageSrc && <img className="ph-img" src={imageSrc} alt={imageAlt} loading="lazy" />}
              {!imageSrc && photoTag && <span className="ph-tag">{photoTag}</span>}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function StatRow({ items }) {
  return (
    <section className="tight">
      <div className="stat-row">
        {items.map((it, i) => (
          <div className="cell" key={i}>
            <div className="num">{it.num}</div>
            <div className="lab">{it.lab}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

const G_SHAPES = ['s-tall', 's-portrait', 's-square', 's-landscape', 's-portrait', 's-pano', 's-tall', 's-square', 's-portrait', 's-landscape', 's-tall', 's-portrait'];
const G_VARS = ['a','b','c','d','e','a','b','c','d','e','a','b'];

function Gallery({ eyebrow, title, sub, count = 12, tag = 'placeholder', images }) {
  const total = images ? images.length : count;
  return (
    <section className="cream">
      <div className="container">
        <div className="section-head-c reveal">
          {eyebrow && <span className="eyebrow">{eyebrow}</span>}
          {title && <h2 className="section-title">{title}</h2>}
          {sub && <p>{sub}</p>}
        </div>
        <div className="gallery-masonry reveal-stagger">
          {Array.from({ length: total }, (_, i) => (
            <div className={'item ' + (images && images[i] && typeof images[i] === 'object' && images[i].shape ? images[i].shape : G_SHAPES[i % G_SHAPES.length])} key={i}>
              <div className={'ph variant-' + G_VARS[i % G_VARS.length]}>
                {images && images[i]
                  ? (() => { const item = images[i]; const src = typeof item === 'object' ? item.src : item; const pos = typeof item === 'object' && item.objectPosition ? item.objectPosition : undefined; return <img className="ph-img" src={src} alt="" loading="lazy" style={pos ? { objectPosition: pos } : undefined} />; })()
                  : <span className="ph-tag">{tag} · {String(i + 1).padStart(2, '0')}</span>
                }
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Process({ eyebrow, title, steps }) {
  return (
    <section>
      <div className="container">
        <div className="reveal" style={{ marginBottom: 8 }}>
          {eyebrow && <span className="eyebrow">{eyebrow}</span>}
          {title && <h2 className="section-title">{title}</h2>}
        </div>
        <div className="process reveal-stagger">
          {steps.map((s, i) => (
            <div className="step" key={i}>
              <div className="n">Step {String(i + 1).padStart(2, '0')}</div>
              <h3>{s.title}</h3>
              <p>{s.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Packages({ eyebrow, title, sub, items, featuredIndex = 1, note, variant }) {
  return (
    <section className="cream">
      <div className="container">
        <div className="section-head-c reveal">
          {eyebrow && <span className="eyebrow">{eyebrow}</span>}
          {title && <h2 className="section-title">{title}</h2>}
          {sub && <p>{sub}</p>}
        </div>
        <div className={'packages reveal-stagger' + (variant ? ' packages--' + variant : '')}>
          {items.map((p, i) => (
            <div className={'pkg' + (i === featuredIndex ? ' featured' : '')} key={p.name}>
              {i === featuredIndex && <span className="tag">Most chosen</span>}
              <h3>{p.name}</h3>
              <div className="price">${p.price}<small> {p.unit || 'AUD'}</small></div>
              <ul>{p.items.map((it, j) => <li key={j}>{it}</li>)}</ul>
              <a href="#enquire" className="btn">Enquire <span className="arr">→</span></a>
            </div>
          ))}
        </div>
        {note && <p style={{ textAlign: 'center', marginTop: 36, color: 'var(--charcoal)', fontSize: 14 }}>{note}</p>}
      </div>
    </section>
  );
}

function PackagesGrid({ eyebrow, title, sub, items, note }) {
  return (
    <section className="cream">
      <div className="container">
        <div className="section-head-c reveal">
          {eyebrow && <span className="eyebrow">{eyebrow}</span>}
          {title && <h2 className="section-title">{title}</h2>}
          {sub && <p>{sub}</p>}
        </div>
        <div className="pkg-grid reveal-stagger">
          {items.map((p) => (
            <div className="pkg-card" key={p.name}>
              <div className="pkg-card-photo">
                {p.image && <img src={p.image} alt="" loading="lazy" />}
              </div>
              <div className="pkg-card-body">
                <div className="pkg-meta">{p.duration} · {p.photos} photos</div>
                <h3>{p.name}</h3>
                <div className="price">${p.price}<small> Inc. GST</small></div>
                <p className="pkg-best">Best for: {p.bestFor}</p>
                <a href="#enquire" className="btn">Enquire <span className="arr">→</span></a>
              </div>
            </div>
          ))}
        </div>
        {note && <p style={{ textAlign: 'center', marginTop: 36, color: 'var(--charcoal)', fontSize: 14 }}>{note}</p>}
      </div>
    </section>
  );
}

function Quote({ quote, name, where, loyalty }) {
  return (
    <section>
      <div className="container">
        <div className="quote-block reveal">
          <div className="mark">"</div>
          <blockquote>{quote}</blockquote>
          <div className="who">
            <strong>{name}</strong>
            {where}{loyalty ? ' · ' + loyalty : ''}
          </div>
        </div>
      </div>
    </section>
  );
}

function ContactForm({ variant = 'personal', eyebrow, title, sub }) {
  const [status, setStatus] = useStateP('idle'); // 'idle' | 'sending' | 'sent' | 'error'
  const [windowVal, setWindowVal] = useStateP('');

  useEffectP(() => {
    if (variant !== 'maternity') return;
    const handler = (e) => {
      setWindowVal(e.detail);
      const el = document.getElementById('enquire');
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    };
    window.addEventListener('fill-maternity-window', handler);
    return () => window.removeEventListener('fill-maternity-window', handler);
  }, [variant]);

  const personalFields = [
    { id: 'name', label: 'Your name', type: 'text', required: true },
    { id: 'email', label: 'Email', type: 'email', required: true },
    { id: 'phone', label: 'Phone', type: 'tel' },
    { id: 'session', label: 'Session type', type: 'select', options: ['Maternity', 'Newborn', 'Families', 'Couples & Engagements', 'Weddings & Elopements', 'Not sure yet'] },
    { id: 'date', label: 'Preferred date', type: 'date' },
    { id: 'found', label: 'How did you find me?', type: 'text' },
    { id: 'message', label: 'Tell me more', type: 'textarea', full: true, required: true },
  ];

  const brandFields = [
    { id: 'name', label: 'Your name', type: 'text', required: true },
    { id: 'brand', label: 'Brand name', type: 'text', required: true },
    { id: 'email', label: 'Email', type: 'email', required: true },
    { id: 'website', label: 'Website or Instagram', type: 'text' },
    { id: 'type', label: 'Type of content', type: 'select', options: ['Half-day lifestyle', 'Full-day lifestyle', 'Product in use', 'Campaign', 'Ongoing content', 'Not sure yet'] },
    { id: 'window', label: 'Shoot date range', type: 'text' },
    { id: 'brief', label: 'Brief description', type: 'textarea', full: true, required: true },
  ];

  const maternityFields = [
    { id: 'name', label: 'Your name', type: 'text', required: true },
    { id: 'email', label: 'Email', type: 'email', required: true },
    { id: 'phone', label: 'Phone', type: 'tel' },
    { id: 'due', label: 'Due date', type: 'date' },
    { id: 'window', label: 'Recommended photo window', type: 'text', helper: 'Auto-filled from the calculator above' },
    { id: 'date', label: 'Preferred session date', type: 'date' },
    { id: 'message', label: 'Tell me more', type: 'textarea', full: true, required: true },
  ];

  const weddingFields = [
    { id: 'name', label: 'Your name', type: 'text', required: true },
    { id: 'partner', label: "Partner's name", type: 'text' },
    { id: 'email', label: 'Email', type: 'email', required: true },
    { id: 'date', label: 'Wedding date', type: 'date' },
    { id: 'location', label: 'Location or venue', type: 'text' },
    { id: 'guests', label: 'Guest count', type: 'text' },
    { id: 'found', label: 'How did you hear about me?', type: 'text' },
    { id: 'message', label: 'Tell me about your day', type: 'textarea', full: true, required: true },
  ];

  const fields = variant === 'brand' ? brandFields
    : variant === 'maternity' ? maternityFields
    : variant === 'wedding' ? weddingFields
    : personalFields;

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus('sending');
    try {
      const res = await fetch('https://formspree.io/f/xojrzlyo', {
        method: 'POST',
        body: new FormData(e.target),
        headers: { Accept: 'application/json' },
      });
      if (res.ok) {
        console.log('Lead event fired');
        if (typeof fbq === 'function') fbq('track', 'Lead');
        setStatus('sent');
      } else {
        const data = await res.json().catch(() => ({}));
        console.error('Formspree error', res.status, data);
        setStatus('error');
      }
    } catch (err) {
      console.error('Form submit error', err);
      setStatus('error');
    }
  };

  return (
    <section id="enquire">
      <div className="container">
        <div className="form-block reveal">
          <div className="copy">
            {eyebrow && <span className="eyebrow">{eyebrow}</span>}
            {title && <h2 className="section-title">{title}</h2>}
            {sub && <p>{sub}</p>}
            <div className="contact-direct">
              <span className="label">Or reach out directly</span>
              <div className="val"><a href={_eml()}>{_em()}</a></div>
              <span className="label">Phone</span>
              <div className="val">0479 039 539</div>
            </div>
          </div>
          {status === 'sent' ? (
            <div className="full form-success">Thanks — your enquiry came through. I'll be in touch shortly.</div>
          ) : (
            <form className="form-grid" onSubmit={handleSubmit}>
              {fields.map(f => (
                <div className={'field' + (f.full ? ' full' : '')} key={f.id}>
                  <label htmlFor={f.id}>{f.label}{f.required && ' *'}</label>
                  {f.type === 'textarea' ? (
                    <textarea id={f.id} name={f.id} required={f.required} />
                  ) : f.type === 'select' ? (
                    <select id={f.id} name={f.id}>
                      <option value="">Choose one</option>
                      {f.options.map(o => <option key={o}>{o}</option>)}
                    </select>
                  ) : f.id === 'window' && variant === 'maternity' ? (
                    <input id={f.id} name={f.id} type={f.type} value={windowVal} onChange={e => setWindowVal(e.target.value)} />
                  ) : (
                    <input id={f.id} name={f.id} type={f.type} required={f.required} />
                  )}
                  {f.helper && <span className="helper">{f.helper}</span>}
                </div>
              ))}
              <div className="full actions">
                <button type="submit" className="btn" disabled={status === 'sending'}>Send enquiry <span className="arr">→</span></button>
                <span style={{ fontSize: 12, color: 'var(--charcoal)', opacity: 0.7 }}>I'll reply within 24 hours.</span>
              </div>
              {status === 'error' && <div className="full form-success" style={{color:'var(--accent)'}}>Something went wrong. Please try again or email <a href={_eml()}>{_em()}</a> directly.</div>}
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

function MaternityCalc() {
  const [due, setDue] = useStateP('');
  const result = useMemo(() => {
    if (!due) return null;
    const d = new Date(due);
    if (isNaN(d)) return null;
    const fmt = dt => dt.toLocaleDateString('en-AU', { day: 'numeric', month: 'long' });
    const conception = new Date(d.getTime() - 280 * 86400000);
    const w28 = new Date(conception.getTime() + 28 * 7 * 86400000);
    const w31 = new Date(conception.getTime() + 31 * 7 * 86400000);
    const w34 = new Date(conception.getTime() + 34 * 7 * 86400000);
    return { ideal: `${fmt(w28)} — ${fmt(w34)}`, sweet: fmt(w31) };
  }, [due]);

  return (
    <section id="maternity-calc">
      <div className="container">
        <div className="reveal" style={{ marginBottom: 36 }}>
          <span className="eyebrow">Timing calculator</span>
          <h2 className="section-title" style={{ maxWidth: '20ch' }}>When is the right week?</h2>
          <p className="lead" style={{ marginTop: 18 }}>Most maternity sessions feel best between 28 and 34 weeks. Drop in your due date and I'll show you your window.</p>
        </div>
        <div className="calc reveal">
          <div className="input-side">
            <div className="field">
              <label>Due date</label>
              <input type="date" value={due} onChange={e => setDue(e.target.value)} />
              <span className="helper">We'll work out a 28–34 week window. The sweet spot is usually around 31.</span>
            </div>
          </div>
          <div className="out">
            <div className="row">
              <div className="lab">Ideal session window</div>
              <div className="big">{result ? result.ideal : 'Pick a date →'}</div>
            </div>
            <div className="row">
              <div className="lab">Sweet spot (31 weeks)</div>
              <div className="big">{result ? result.sweet : '—'}</div>
            </div>
            {result && (
              <div style={{ marginTop: 24 }}>
                <p style={{ fontSize: 13, color: 'var(--charcoal)', marginBottom: 10 }}>Dates look right? Add them straight to your enquiry.</p>
                <button
                  type="button"
                  className="btn"
                  onClick={() => window.dispatchEvent(new CustomEvent('fill-maternity-window', { detail: result.ideal }))}
                >
                  Add to my enquiry <span className="arr">→</span>
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function PageFooter() {
  const base = pageBase();
  const L = window.__navLinks || {};
  return (
    <footer>
      <div className="container">
        <div className="foot-top">
          <div className="logo-row">
            <img src={base + 'assets/logo.webp'} alt="JPaz Photography" />
            <p className="blurb">Sydney lifestyle photographer creating genuine content that shows the real feeling of your brand, your products and your life.</p>
          </div>
          <div>
            <h4>Personal</h4>
            <ul>
              <li><a href={L.maternity}>Maternity</a></li>
              <li><a href={L.newborn}>Newborn</a></li>
              <li><a href={L.families}>Families</a></li>
              <li><a href={L.couples}>Couples</a></li>
              <li><a href={L.weddings}>Weddings</a></li>
            </ul>
          </div>
          <div>
            <h4>Studio</h4>
            <ul>
              <li><a href={L.brand}>Brand &amp; Lifestyle</a></li>
              <li><a href={L.about}>About Jorge</a></li>
              <li><a href={L.blog}>Journal</a></li>
              <li><a href={L.contact}>Contact</a></li>
            </ul>
          </div>
          <div>
            <h4>Elsewhere</h4>
            <ul>
              <li><a href="https://www.instagram.com/jpaz.photography" target="_blank" rel="noopener noreferrer">Instagram</a></li>
              <li><a href="https://jpazphotography.pic-time.com/client" target="_blank" rel="noopener noreferrer">Client galleries</a></li>
              <li><a href={_eml()}>{_em()}</a></li>
              <li><a href="tel:+61479039539">0479 039 539</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© 2026 JPaz Photography. All rights reserved.</span>
          <div className="foot-legal">
            <a href="privacy-policy.html">Privacy Policy</a>
            <a href="terms-conditions.html">Terms &amp; Conditions</a>
          </div>
          <span className="ack">I acknowledge the Gayamaygal and Garigal people, the traditional custodians of the land on which I live and work, and pay my respects to their Elders past, present and emerging.</span>
        </div>
      </div>
    </footer>
  );
}

const BRAND_NAMES = [
  'Willow Sage', 'Sunrise Breath', 'North Cove Co', 'Bare & Bloom',
  'The Good Shore', 'Tide & Oak', 'Coastal & Co', 'Sonder Studio',
];

function BrandMarquee() {
  const doubled = [...BRAND_NAMES, ...BRAND_NAMES];
  return (
    <section className="brand-marquee">
      <div className="marquee-head reveal">
        <span className="eyebrow">In good company</span>
        <h2 className="section-title">A few of the brands I&apos;ve worked with.</h2>
      </div>
      <div className="marquee-track">
        <div className="marquee-inner">
          {doubled.map((name, i) => (
            <React.Fragment key={i}>
              <div className="marquee-logo">
                <span className="marquee-name">{name}</span>
              </div>
              <span className="marquee-sep" role="presentation" />
            </React.Fragment>
          ))}
        </div>
      </div>
    </section>
  );
}

window.PageHero = PageHero;
window.SplitBlock = SplitBlock;
window.StatRow = StatRow;
window.BrandMarquee = BrandMarquee;
window.Gallery = Gallery;
window.Process = Process;
window.Packages = Packages;
window.PackagesGrid = PackagesGrid;
window.Quote = Quote;
window.ContactForm = ContactForm;
window.MaternityCalc = MaternityCalc;
window.PageFooter = PageFooter;
