// ═══════════════════════════════════════════════════════════════
//  Aurelle Bride — app.jsx
//  Public-facing site. Depends on components.jsx loading first.
// ═══════════════════════════════════════════════════════════════

// ── reCAPTCHA v3 helper ───────────────────────────────────────
const RECAPTCHA_SITE_KEY = '6LeWlucsAAAAAOMkcMc9P5IlDD6YqHUM7XZThNIL';

function getRecaptchaToken(action) {
  return new Promise((resolve) => {
    if (typeof grecaptcha === 'undefined') { resolve(''); return; }
    grecaptcha.ready(() => {
      grecaptcha.execute(RECAPTCHA_SITE_KEY, { action })
        .then(resolve)
        .catch(() => resolve(''));
    });
  });
}

// ── Cursor follower ───────────────────────────────────────────
(function () {
  const dot = document.getElementById('cursor');
  if (!dot) return;
  document.addEventListener('mousemove', e => {
    dot.style.transform = `translate(${e.clientX}px, ${e.clientY}px) translate(-50%,-50%)`;
  });
  document.querySelectorAll('a,button,[role=button]').forEach(el => {
    el.addEventListener('mouseenter', () => dot.classList.add('hover'));
    el.addEventListener('mouseleave', () => dot.classList.remove('hover'));
  });
})();

// ──────────────────────────────────────────────────────────────
//  SITE NAV
// ──────────────────────────────────────────────────────────────

// ── Phone-number input with auto-detected country dial code ──
const DIAL_CODES = [
  // ── Popular / most likely Aurelle customers first ──
  { code: 'PK', dial: '+92',  flag: '🇵🇰', name: 'Pakistan' },
  { code: 'AE', dial: '+971', flag: '🇦🇪', name: 'United Arab Emirates' },
  { code: 'SA', dial: '+966', flag: '🇸🇦', name: 'Saudi Arabia' },
  { code: 'GB', dial: '+44',  flag: '🇬🇧', name: 'United Kingdom' },
  { code: 'US', dial: '+1',   flag: '🇺🇸', name: 'United States' },
  { code: 'CA', dial: '+1',   flag: '🇨🇦', name: 'Canada' },
  { code: 'AU', dial: '+61',  flag: '🇦🇺', name: 'Australia' },
  { code: 'IN', dial: '+91',  flag: '🇮🇳', name: 'India' },
  { code: 'QA', dial: '+974', flag: '🇶🇦', name: 'Qatar' },
  { code: 'KW', dial: '+965', flag: '🇰🇼', name: 'Kuwait' },
  { code: 'BH', dial: '+973', flag: '🇧🇭', name: 'Bahrain' },
  { code: 'OM', dial: '+968', flag: '🇴🇲', name: 'Oman' },
  { code: 'MY', dial: '+60',  flag: '🇲🇾', name: 'Malaysia' },
  { code: 'SG', dial: '+65',  flag: '🇸🇬', name: 'Singapore' },
  { code: 'BD', dial: '+880', flag: '🇧🇩', name: 'Bangladesh' },
  // ── A ──
  { code: 'AF', dial: '+93',  flag: '🇦🇫', name: 'Afghanistan' },
  { code: 'AL', dial: '+355', flag: '🇦🇱', name: 'Albania' },
  { code: 'DZ', dial: '+213', flag: '🇩🇿', name: 'Algeria' },
  { code: 'AD', dial: '+376', flag: '🇦🇩', name: 'Andorra' },
  { code: 'AO', dial: '+244', flag: '🇦🇴', name: 'Angola' },
  { code: 'AG', dial: '+1268',flag: '🇦🇬', name: 'Antigua & Barbuda' },
  { code: 'AR', dial: '+54',  flag: '🇦🇷', name: 'Argentina' },
  { code: 'AM', dial: '+374', flag: '🇦🇲', name: 'Armenia' },
  { code: 'AT', dial: '+43',  flag: '🇦🇹', name: 'Austria' },
  { code: 'AZ', dial: '+994', flag: '🇦🇿', name: 'Azerbaijan' },
  // ── B ──
  { code: 'BS', dial: '+1242',flag: '🇧🇸', name: 'Bahamas' },
  { code: 'BB', dial: '+1246',flag: '🇧🇧', name: 'Barbados' },
  { code: 'BY', dial: '+375', flag: '🇧🇾', name: 'Belarus' },
  { code: 'BE', dial: '+32',  flag: '🇧🇪', name: 'Belgium' },
  { code: 'BZ', dial: '+501', flag: '🇧🇿', name: 'Belize' },
  { code: 'BJ', dial: '+229', flag: '🇧🇯', name: 'Benin' },
  { code: 'BT', dial: '+975', flag: '🇧🇹', name: 'Bhutan' },
  { code: 'BO', dial: '+591', flag: '🇧🇴', name: 'Bolivia' },
  { code: 'BA', dial: '+387', flag: '🇧🇦', name: 'Bosnia & Herzegovina' },
  { code: 'BW', dial: '+267', flag: '🇧🇼', name: 'Botswana' },
  { code: 'BR', dial: '+55',  flag: '🇧🇷', name: 'Brazil' },
  { code: 'BN', dial: '+673', flag: '🇧🇳', name: 'Brunei' },
  { code: 'BG', dial: '+359', flag: '🇧🇬', name: 'Bulgaria' },
  { code: 'BF', dial: '+226', flag: '🇧🇫', name: 'Burkina Faso' },
  { code: 'BI', dial: '+257', flag: '🇧🇮', name: 'Burundi' },
  // ── C ──
  { code: 'CV', dial: '+238', flag: '🇨🇻', name: 'Cabo Verde' },
  { code: 'KH', dial: '+855', flag: '🇰🇭', name: 'Cambodia' },
  { code: 'CM', dial: '+237', flag: '🇨🇲', name: 'Cameroon' },
  { code: 'CF', dial: '+236', flag: '🇨🇫', name: 'Central African Rep.' },
  { code: 'TD', dial: '+235', flag: '🇹🇩', name: 'Chad' },
  { code: 'CL', dial: '+56',  flag: '🇨🇱', name: 'Chile' },
  { code: 'CN', dial: '+86',  flag: '🇨🇳', name: 'China' },
  { code: 'CO', dial: '+57',  flag: '🇨🇴', name: 'Colombia' },
  { code: 'KM', dial: '+269', flag: '🇰🇲', name: 'Comoros' },
  { code: 'CD', dial: '+243', flag: '🇨🇩', name: 'Congo (DRC)' },
  { code: 'CG', dial: '+242', flag: '🇨🇬', name: 'Congo (Republic)' },
  { code: 'CR', dial: '+506', flag: '🇨🇷', name: 'Costa Rica' },
  { code: 'HR', dial: '+385', flag: '🇭🇷', name: 'Croatia' },
  { code: 'CU', dial: '+53',  flag: '🇨🇺', name: 'Cuba' },
  { code: 'CY', dial: '+357', flag: '🇨🇾', name: 'Cyprus' },
  { code: 'CZ', dial: '+420', flag: '🇨🇿', name: 'Czech Republic' },
  // ── D ──
  { code: 'DK', dial: '+45',  flag: '🇩🇰', name: 'Denmark' },
  { code: 'DJ', dial: '+253', flag: '🇩🇯', name: 'Djibouti' },
  { code: 'DM', dial: '+1767',flag: '🇩🇲', name: 'Dominica' },
  { code: 'DO', dial: '+1809',flag: '🇩🇴', name: 'Dominican Republic' },
  // ── E ──
  { code: 'EC', dial: '+593', flag: '🇪🇨', name: 'Ecuador' },
  { code: 'EG', dial: '+20',  flag: '🇪🇬', name: 'Egypt' },
  { code: 'SV', dial: '+503', flag: '🇸🇻', name: 'El Salvador' },
  { code: 'GQ', dial: '+240', flag: '🇬🇶', name: 'Equatorial Guinea' },
  { code: 'ER', dial: '+291', flag: '🇪🇷', name: 'Eritrea' },
  { code: 'EE', dial: '+372', flag: '🇪🇪', name: 'Estonia' },
  { code: 'SZ', dial: '+268', flag: '🇸🇿', name: 'Eswatini' },
  { code: 'ET', dial: '+251', flag: '🇪🇹', name: 'Ethiopia' },
  // ── F ──
  { code: 'FJ', dial: '+679', flag: '🇫🇯', name: 'Fiji' },
  { code: 'FI', dial: '+358', flag: '🇫🇮', name: 'Finland' },
  { code: 'FR', dial: '+33',  flag: '🇫🇷', name: 'France' },
  { code: 'GA', dial: '+241', flag: '🇬🇦', name: 'Gabon' },
  { code: 'GM', dial: '+220', flag: '🇬🇲', name: 'Gambia' },
  // ── G ──
  { code: 'GE', dial: '+995', flag: '🇬🇪', name: 'Georgia' },
  { code: 'DE', dial: '+49',  flag: '🇩🇪', name: 'Germany' },
  { code: 'GH', dial: '+233', flag: '🇬🇭', name: 'Ghana' },
  { code: 'GR', dial: '+30',  flag: '🇬🇷', name: 'Greece' },
  { code: 'GD', dial: '+1473',flag: '🇬🇩', name: 'Grenada' },
  { code: 'GT', dial: '+502', flag: '🇬🇹', name: 'Guatemala' },
  { code: 'GN', dial: '+224', flag: '🇬🇳', name: 'Guinea' },
  { code: 'GW', dial: '+245', flag: '🇬🇼', name: 'Guinea-Bissau' },
  { code: 'GY', dial: '+592', flag: '🇬🇾', name: 'Guyana' },
  // ── H ──
  { code: 'HT', dial: '+509', flag: '🇭🇹', name: 'Haiti' },
  { code: 'HN', dial: '+504', flag: '🇭🇳', name: 'Honduras' },
  { code: 'HK', dial: '+852', flag: '🇭🇰', name: 'Hong Kong' },
  { code: 'HU', dial: '+36',  flag: '🇭🇺', name: 'Hungary' },
  // ── I ──
  { code: 'IS', dial: '+354', flag: '🇮🇸', name: 'Iceland' },
  { code: 'ID', dial: '+62',  flag: '🇮🇩', name: 'Indonesia' },
  { code: 'IR', dial: '+98',  flag: '🇮🇷', name: 'Iran' },
  { code: 'IQ', dial: '+964', flag: '🇮🇶', name: 'Iraq' },
  { code: 'IE', dial: '+353', flag: '🇮🇪', name: 'Ireland' },
  { code: 'IL', dial: '+972', flag: '🇮🇱', name: 'Israel' },
  { code: 'IT', dial: '+39',  flag: '🇮🇹', name: 'Italy' },
  // ── J ──
  { code: 'JM', dial: '+1876',flag: '🇯🇲', name: 'Jamaica' },
  { code: 'JP', dial: '+81',  flag: '🇯🇵', name: 'Japan' },
  { code: 'JO', dial: '+962', flag: '🇯🇴', name: 'Jordan' },
  // ── K ──
  { code: 'KZ', dial: '+7',   flag: '🇰🇿', name: 'Kazakhstan' },
  { code: 'KE', dial: '+254', flag: '🇰🇪', name: 'Kenya' },
  { code: 'KI', dial: '+686', flag: '🇰🇮', name: 'Kiribati' },
  { code: 'KP', dial: '+850', flag: '🇰🇵', name: 'North Korea' },
  { code: 'KR', dial: '+82',  flag: '🇰🇷', name: 'South Korea' },
  { code: 'XK', dial: '+383', flag: '🇽🇰', name: 'Kosovo' },
  { code: 'KG', dial: '+996', flag: '🇰🇬', name: 'Kyrgyzstan' },
  // ── L ──
  { code: 'LA', dial: '+856', flag: '🇱🇦', name: 'Laos' },
  { code: 'LV', dial: '+371', flag: '🇱🇻', name: 'Latvia' },
  { code: 'LB', dial: '+961', flag: '🇱🇧', name: 'Lebanon' },
  { code: 'LS', dial: '+266', flag: '🇱🇸', name: 'Lesotho' },
  { code: 'LR', dial: '+231', flag: '🇱🇷', name: 'Liberia' },
  { code: 'LY', dial: '+218', flag: '🇱🇾', name: 'Libya' },
  { code: 'LI', dial: '+423', flag: '🇱🇮', name: 'Liechtenstein' },
  { code: 'LT', dial: '+370', flag: '🇱🇹', name: 'Lithuania' },
  { code: 'LU', dial: '+352', flag: '🇱🇺', name: 'Luxembourg' },
  // ── M ──
  { code: 'MO', dial: '+853', flag: '🇲🇴', name: 'Macau' },
  { code: 'MG', dial: '+261', flag: '🇲🇬', name: 'Madagascar' },
  { code: 'MW', dial: '+265', flag: '🇲🇼', name: 'Malawi' },
  { code: 'MV', dial: '+960', flag: '🇲🇻', name: 'Maldives' },
  { code: 'ML', dial: '+223', flag: '🇲🇱', name: 'Mali' },
  { code: 'MT', dial: '+356', flag: '🇲🇹', name: 'Malta' },
  { code: 'MH', dial: '+692', flag: '🇲🇭', name: 'Marshall Islands' },
  { code: 'MR', dial: '+222', flag: '🇲🇷', name: 'Mauritania' },
  { code: 'MU', dial: '+230', flag: '🇲🇺', name: 'Mauritius' },
  { code: 'MX', dial: '+52',  flag: '🇲🇽', name: 'Mexico' },
  { code: 'FM', dial: '+691', flag: '🇫🇲', name: 'Micronesia' },
  { code: 'MD', dial: '+373', flag: '🇲🇩', name: 'Moldova' },
  { code: 'MC', dial: '+377', flag: '🇲🇨', name: 'Monaco' },
  { code: 'MN', dial: '+976', flag: '🇲🇳', name: 'Mongolia' },
  { code: 'ME', dial: '+382', flag: '🇲🇪', name: 'Montenegro' },
  { code: 'MA', dial: '+212', flag: '🇲🇦', name: 'Morocco' },
  { code: 'MZ', dial: '+258', flag: '🇲🇿', name: 'Mozambique' },
  { code: 'MM', dial: '+95',  flag: '🇲🇲', name: 'Myanmar' },
  // ── N ──
  { code: 'NA', dial: '+264', flag: '🇳🇦', name: 'Namibia' },
  { code: 'NR', dial: '+674', flag: '🇳🇷', name: 'Nauru' },
  { code: 'NP', dial: '+977', flag: '🇳🇵', name: 'Nepal' },
  { code: 'NL', dial: '+31',  flag: '🇳🇱', name: 'Netherlands' },
  { code: 'NZ', dial: '+64',  flag: '🇳🇿', name: 'New Zealand' },
  { code: 'NI', dial: '+505', flag: '🇳🇮', name: 'Nicaragua' },
  { code: 'NE', dial: '+227', flag: '🇳🇪', name: 'Niger' },
  { code: 'NG', dial: '+234', flag: '🇳🇬', name: 'Nigeria' },
  { code: 'MK', dial: '+389', flag: '🇲🇰', name: 'North Macedonia' },
  { code: 'NO', dial: '+47',  flag: '🇳🇴', name: 'Norway' },
  // ── O–P ──
  { code: 'PW', dial: '+680', flag: '🇵🇼', name: 'Palau' },
  { code: 'PS', dial: '+970', flag: '🇵🇸', name: 'Palestine' },
  { code: 'PA', dial: '+507', flag: '🇵🇦', name: 'Panama' },
  { code: 'PG', dial: '+675', flag: '🇵🇬', name: 'Papua New Guinea' },
  { code: 'PY', dial: '+595', flag: '🇵🇾', name: 'Paraguay' },
  { code: 'PE', dial: '+51',  flag: '🇵🇪', name: 'Peru' },
  { code: 'PH', dial: '+63',  flag: '🇵🇭', name: 'Philippines' },
  { code: 'PL', dial: '+48',  flag: '🇵🇱', name: 'Poland' },
  { code: 'PT', dial: '+351', flag: '🇵🇹', name: 'Portugal' },
  // ── R ──
  { code: 'RO', dial: '+40',  flag: '🇷🇴', name: 'Romania' },
  { code: 'RU', dial: '+7',   flag: '🇷🇺', name: 'Russia' },
  { code: 'RW', dial: '+250', flag: '🇷🇼', name: 'Rwanda' },
  // ── S ──
  { code: 'KN', dial: '+1869',flag: '🇰🇳', name: 'Saint Kitts & Nevis' },
  { code: 'LC', dial: '+1758',flag: '🇱🇨', name: 'Saint Lucia' },
  { code: 'VC', dial: '+1784',flag: '🇻🇨', name: 'Saint Vincent' },
  { code: 'WS', dial: '+685', flag: '🇼🇸', name: 'Samoa' },
  { code: 'SM', dial: '+378', flag: '🇸🇲', name: 'San Marino' },
  { code: 'ST', dial: '+239', flag: '🇸🇹', name: 'São Tomé & Príncipe' },
  { code: 'SN', dial: '+221', flag: '🇸🇳', name: 'Senegal' },
  { code: 'RS', dial: '+381', flag: '🇷🇸', name: 'Serbia' },
  { code: 'SC', dial: '+248', flag: '🇸🇨', name: 'Seychelles' },
  { code: 'SL', dial: '+232', flag: '🇸🇱', name: 'Sierra Leone' },
  { code: 'SK', dial: '+421', flag: '🇸🇰', name: 'Slovakia' },
  { code: 'SI', dial: '+386', flag: '🇸🇮', name: 'Slovenia' },
  { code: 'SB', dial: '+677', flag: '🇸🇧', name: 'Solomon Islands' },
  { code: 'SO', dial: '+252', flag: '🇸🇴', name: 'Somalia' },
  { code: 'ZA', dial: '+27',  flag: '🇿🇦', name: 'South Africa' },
  { code: 'SS', dial: '+211', flag: '🇸🇸', name: 'South Sudan' },
  { code: 'ES', dial: '+34',  flag: '🇪🇸', name: 'Spain' },
  { code: 'LK', dial: '+94',  flag: '🇱🇰', name: 'Sri Lanka' },
  { code: 'SD', dial: '+249', flag: '🇸🇩', name: 'Sudan' },
  { code: 'SR', dial: '+597', flag: '🇸🇷', name: 'Suriname' },
  { code: 'SE', dial: '+46',  flag: '🇸🇪', name: 'Sweden' },
  { code: 'CH', dial: '+41',  flag: '🇨🇭', name: 'Switzerland' },
  { code: 'SY', dial: '+963', flag: '🇸🇾', name: 'Syria' },
  // ── T ──
  { code: 'TW', dial: '+886', flag: '🇹🇼', name: 'Taiwan' },
  { code: 'TJ', dial: '+992', flag: '🇹🇯', name: 'Tajikistan' },
  { code: 'TZ', dial: '+255', flag: '🇹🇿', name: 'Tanzania' },
  { code: 'TH', dial: '+66',  flag: '🇹🇭', name: 'Thailand' },
  { code: 'TL', dial: '+670', flag: '🇹🇱', name: 'Timor-Leste' },
  { code: 'TG', dial: '+228', flag: '🇹🇬', name: 'Togo' },
  { code: 'TO', dial: '+676', flag: '🇹🇴', name: 'Tonga' },
  { code: 'TT', dial: '+1868',flag: '🇹🇹', name: 'Trinidad & Tobago' },
  { code: 'TN', dial: '+216', flag: '🇹🇳', name: 'Tunisia' },
  { code: 'TR', dial: '+90',  flag: '🇹🇷', name: 'Turkey' },
  { code: 'TM', dial: '+993', flag: '🇹🇲', name: 'Turkmenistan' },
  { code: 'TV', dial: '+688', flag: '🇹🇻', name: 'Tuvalu' },
  // ── U ──
  { code: 'UG', dial: '+256', flag: '🇺🇬', name: 'Uganda' },
  { code: 'UA', dial: '+380', flag: '🇺🇦', name: 'Ukraine' },
  { code: 'UY', dial: '+598', flag: '🇺🇾', name: 'Uruguay' },
  { code: 'UZ', dial: '+998', flag: '🇺🇿', name: 'Uzbekistan' },
  // ── V ──
  { code: 'VU', dial: '+678', flag: '🇻🇺', name: 'Vanuatu' },
  { code: 'VE', dial: '+58',  flag: '🇻🇪', name: 'Venezuela' },
  { code: 'VN', dial: '+84',  flag: '🇻🇳', name: 'Vietnam' },
  // ── Y–Z ──
  { code: 'YE', dial: '+967', flag: '🇾🇪', name: 'Yemen' },
  { code: 'ZM', dial: '+260', flag: '🇿🇲', name: 'Zambia' },
  { code: 'ZW', dial: '+263', flag: '🇿🇼', name: 'Zimbabwe' },
];

// Map currency.jsx country_code → dial entry
const COUNTRY_TO_DIAL = {};
DIAL_CODES.forEach(d => { COUNTRY_TO_DIAL[d.code] = d; });

function useAutoDialCode() {
  const [dialEntry, setDialEntry] = React.useState(DIAL_CODES[0]); // default PK
  React.useEffect(() => {
    try {
      const cached = JSON.parse(localStorage.getItem('ab_geo_v2') || '{}');
      const cc = cached.country_code;
      if (cc && COUNTRY_TO_DIAL[cc]) setDialEntry(COUNTRY_TO_DIAL[cc]);
    } catch {}
  }, []);
  return [dialEntry, setDialEntry];
}

function PhoneInput({ onChange, required = false, label = 'Phone Number' }) {
  const [dialEntry, setDialEntry] = useAutoDialCode();
  const [open, setOpen] = React.useState(false);
  const [local, setLocal] = React.useState('');
  const [search, setSearch] = React.useState('');

  const filtered = React.useMemo(() => {
    const q = search.toLowerCase().trim();
    if (!q) return DIAL_CODES;
    return DIAL_CODES.filter(d =>
      d.name.toLowerCase().includes(q) || d.dial.includes(q) || d.code.toLowerCase().includes(q)
    );
  }, [search]);

  const pickCountry = (d) => {
    setDialEntry(d);
    setOpen(false);
    setSearch('');
    if (onChange) onChange(d.dial + local);
  };

  const handleType = (e) => {
    const raw = e.target.value.replace(/[^\d\s\-().]/g, '');
    setLocal(raw);
    if (onChange) onChange(dialEntry.dial + raw);
  };

  // Close dropdown on outside click
  const wrapRef = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) { setOpen(false); setSearch(''); } };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  return (
    <Field label={label} required={required}>
      <div style={{ display: 'flex', gap: 0 }}>
        {/* Country code selector */}
        <div style={{ position: 'relative' }} ref={wrapRef}>
          <button
            type="button"
            onClick={() => { setOpen(o => !o); setSearch(''); }}
            style={{
              display: 'flex', alignItems: 'center', gap: 6,
              padding: '0 10px', height: '100%', minHeight: 42,
              background: 'var(--surface-2, #1a1a1a)',
              border: '1px solid var(--line)', borderRight: 'none',
              borderRadius: '6px 0 0 6px', cursor: 'pointer',
              color: 'var(--ink-1)', fontSize: 14, whiteSpace: 'nowrap',
            }}
          >
            <span style={{ fontSize: 18 }}>{dialEntry.flag}</span>
            <span style={{ opacity: 0.8 }}>{dialEntry.dial}</span>
            <span style={{ fontSize: 10, opacity: 0.5 }}>▼</span>
          </button>
          {open && (
            <div style={{
              position: 'absolute', top: '100%', left: 0, zIndex: 9999,
              background: 'var(--surface)', border: '1px solid var(--line)',
              borderRadius: 8, boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
              width: 260, display: 'flex', flexDirection: 'column',
            }}>
              {/* Search box */}
              <div style={{ padding: '8px 10px', borderBottom: '1px solid var(--line)', position: 'sticky', top: 0, background: 'var(--surface)' }}>
                <input
                  autoFocus
                  type="text"
                  placeholder="Search country or code…"
                  value={search}
                  onChange={e => setSearch(e.target.value)}
                  style={{
                    width: '100%', padding: '6px 10px', fontSize: 13,
                    background: 'var(--surface-2, #1a1a1a)',
                    border: '1px solid var(--line)', borderRadius: 6,
                    color: 'var(--ink-1)', outline: 'none',
                  }}
                />
              </div>
              {/* Country list */}
              <div style={{ maxHeight: 240, overflowY: 'auto' }}>
                {filtered.length === 0 && (
                  <div style={{ padding: '14px', fontSize: 13, color: 'var(--ink-3)', textAlign: 'center' }}>No results</div>
                )}
                {filtered.map(d => (
                  <button key={d.code} type="button"
                    onClick={() => pickCountry(d)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 10,
                      width: '100%', padding: '8px 12px',
                      border: 'none', borderBottom: '1px solid var(--line)',
                      cursor: 'pointer', color: 'var(--ink-1)',
                      fontSize: 13, textAlign: 'left',
                      background: d.code === dialEntry.code ? 'rgba(191,155,96,0.12)' : 'transparent',
                    }}
                  >
                    <span style={{ fontSize: 18, lineHeight: 1 }}>{d.flag}</span>
                    <span style={{ flex: 1 }}>{d.name}</span>
                    <span style={{ opacity: 0.55, fontSize: 12 }}>{d.dial}</span>
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>
        {/* Number input */}
        <input
          className="input"
          type="tel"
          placeholder="3XX XXXXXXX"
          value={local}
          onChange={handleType}
          required={required}
          style={{ borderRadius: '0 6px 6px 0', flex: 1 }}
        />
      </div>
    </Field>
  );
}

function SiteNav({ page, setPage, theme, setTheme }) {
  const [menuOpen, setMenuOpen] = useState(false);

  const links = [
    { key: 'home', label: 'Home', path: '/' },
    { key: 'collection', label: 'Collection', path: '/collection' },
    { key: 'custom', label: 'Custom Order', path: '/custom' },
    { key: 'contact', label: 'Contact', path: '/contact' },
  ];

  return (
    <nav className="nav" role="navigation" aria-label="Main navigation">
      <div className="container">
        <div
          className="row"
          style={{
            height: 76,
            justifyContent: 'space-between'
          }}
        >
          {/* Logo */}
          <button
            onClick={() => setPage('home')}
            style={{
              background: 'none',
              border: 'none',
              padding: 0,
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '14px'
            }}
            aria-label="Go to homepage"
          >
            <img
              src="/assets/logo/aurelle-logo.png"
              alt="Aurelle Bride"
              style={{
                height: '56px',
                width: 'auto',
                display: 'block'
              }}
            />

            <span
              style={{
                fontFamily: 'var(--serif)',
                fontSize: '32px',
                fontWeight: 500,
                color: 'var(--ink)',
                letterSpacing: '.04em'
              }}
            >
              Aurelle Bride
            </span>
          </button>

          {/* Desktop nav */}
          <div className="links" role="list">
            {links.map(link => (
              <a
                key={link.key}
                role="listitem"
                href={link.path}
                className={page === link.key ? 'active' : ''}
                onClick={(e) => {
                  e.preventDefault();
                  setPage(link.key);
                  setMenuOpen(false);
                }}
                style={{ cursor: 'pointer' }}
              >
                {link.label}
              </a>
            ))}
          </div>

          {/* Actions */}
          <div className="actions">
            <CurrencyBadge />

            <button
              className="icon-btn"
              title="Toggle theme"
              aria-label="Toggle light/dark theme"
              onClick={() =>
                setTheme(t => t === 'dark' ? 'light' : 'dark')
              }
            >
              {theme === 'dark'
                ? (
                  <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                    <circle cx="12" cy="12" r="5"/>
                    <line x1="12" y1="1" x2="12" y2="3"/>
                    <line x1="12" y1="21" x2="12" y2="23"/>
                    <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>
                    <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
                    <line x1="1" y1="12" x2="3" y2="12"/>
                    <line x1="21" y1="12" x2="23" y2="12"/>
                    <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
                    <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
                  </svg>
                )
                : (
                  <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                    <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
                  </svg>
                )}
            </button>

            {/* Mobile menu */}
            <button
              className="icon-btn"
              style={{ display: 'none' }}
              aria-label="Menu"
              onClick={() => setMenuOpen(o => !o)}
            >
              ☰
            </button>

            <style>{`
              @media(max-width:900px){
                nav .links{display:none!important}
                nav .icon-btn:last-child{display:inline-flex!important}
              }
            `}</style>
          </div>
        </div>

        {/* Mobile nav */}
        {menuOpen && (
          <div
            style={{
              borderTop: '1px solid var(--line)',
              padding: '12px 0 20px',
              display: 'flex',
              flexDirection: 'column',
              gap: 4
            }}
          >
            {links.map(link => (
              <a
                key={link.key}
                href={link.path}
                onClick={(e) => {
                  e.preventDefault();
                  setPage(link.key);
                  setMenuOpen(false);
                }}
                style={{
                  padding: '12px 8px',
                  color: page === link.key
                    ? 'var(--gold)'
                    : 'var(--ink-2)',
                  cursor: 'pointer',
                  fontSize: 15
                }}
              >
                {link.label}
              </a>
            ))}
          </div>
        )}
      </div>
    </nav>
  );
}

// ──────────────────────────────────────────────────────────────
//  WHATSAPP FAB
// ──────────────────────────────────────────────────────────────
function WhatsAppFAB() {
  const wa = (brand.whatsapp || '').replace(/\D/g, '');
  const msg = encodeURIComponent('Hi Aurelle Bride! I\'d love to learn more about your collection.');
  return (
    <div className="fab">
      <a className="pill" href={`https://wa.me/${wa}?text=${msg}`}
        target="_blank" rel="noopener noreferrer" aria-label="Chat on WhatsApp">
        <div className="text">
          <span>Need help? Chat with us</span>
          <strong>WhatsApp</strong>
        </div>
        <div className="wa" aria-hidden="true">
          <svg width="22" height="22" fill="currentColor" viewBox="0 0 24 24">
            <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413z"/>
          </svg>
        </div>
      </a>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
//  HERO
// ──────────────────────────────────────────────────────────────
function HeroSection({ setPage }) {
  return (
    <section className="hero" aria-label="Hero">
      <div className="container">
        <div className="hero-grid">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 36 }}>
            <span className="eyebrow"><span className="dot" aria-hidden="true" />Bridal Couture · Karachi</span>
            <h1 className="display">
              Couture,<br />
              made for <em>you.</em>
            </h1>
            <p className="lead">{brand.heroSub || 'A future-forward bridal atelier.'} Every piece is constructed for one bride — your measurements, your vision, your moment.</p>
            <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
              <button className="btn btn-primary btn-lg" onClick={() => setPage('collection')}>
                Browse Collection
                <svg width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
              </button>
              <button className="btn btn-ghost btn-lg" onClick={() => setPage('custom')}>
                Custom Order
              </button>
            </div>
            <div style={{ display: 'flex', gap: 40, paddingTop: 8 }}>
              {[['6+', 'Silhouettes'], ['100%', 'Made to measure'], ['Worldwide', 'Shipping']].map(([n, l]) => (
                <div key={l}>
                  <div style={{ fontFamily: 'var(--serif)', fontSize: 28, color: 'var(--gold)', fontStyle: 'italic' }}>{n}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--mono)', letterSpacing: '.14em', textTransform: 'uppercase', marginTop: 2 }}>{l}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="hero-art">
            <img src="https://aurellebride.com/uploads/177c6a178b39a0b6_Lehnga.jpg"
              alt="Saffron Veil Lehenga — Aurelle Bride"
              style={{ width: '100%', height: '100%', objectFit: 'cover' }}
              width="600" height="750" />
            <div className="ribbon">
              <span>Latest drop</span>
              <span>Saffron Veil Lehenga · <InlinePrice pkr={268000} /></span>
            </div>
          </div>
        </div>
      </div>
      <div className="scroll-hint" aria-hidden="true">Scroll</div>
    </section>
  );
}

// ──────────────────────────────────────────────────────────────
//  MARQUEE
// ──────────────────────────────────────────────────────────────
function MarqueeStrip() {
  const items = ['Lehenga', 'Sharara', 'Gharara', 'Bridal Gown', 'Anarkali', 'Bridal Mexi', 'Custom Couture'];
  const doubled = [...items, ...items];
  return (
    <div className="marquee" aria-hidden="true">
      <div className="marquee-track">
        {doubled.map((t, i) => <span key={i}>{t}</span>)}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
//  COLLECTION
// ──────────────────────────────────────────────────────────────
function CollectionSection({ onSelectProduct, limit }) {
  const { products, loading } = useProducts();
  const [filter, setFilter] = useState('All');
  const sectionRef = useRef(null);
  useReveal(sectionRef);

  // Listen for filter events from footer navigation links
  useEffect(() => {
    const handler = (e) => setFilter(e.detail || 'All');
    window.addEventListener('set-collection-filter', handler);
    return () => window.removeEventListener('set-collection-filter', handler);
  }, []);

  const categories = useMemo(() => ['All', ...new Set(products.map(p => p.col))], [products]);
  const filtered = filter === 'All' ? products : products.filter(p => p.col === filter);
  const display = limit ? filtered.slice(0, limit) : filtered;

  return (
    <section className="section" ref={sectionRef} aria-labelledby="collection-heading">
      <div className="container">
        <div className="section-head reveal">
          <div>
            <span className="eyebrow" style={{ marginBottom: 12, display: 'block' }}><span className="dot" />The Collection</span>
            <h2 id="collection-heading">Each piece, <em style={{ fontStyle: 'italic', color: 'var(--gold)' }}>singular.</em></h2>
          </div>
          <p>One-of-one silhouettes and bespoke couture — no two brides wear the same dress.</p>
        </div>

        {/* Filter tabs */}
        <div className="tabs reveal" style={{ marginBottom: 40 }} role="tablist" aria-label="Filter by category">
          {categories.map(cat => (
            <button key={cat} role="tab"
              aria-selected={filter === cat}
              className={filter === cat ? 'active' : ''}
              onClick={() => setFilter(cat)}>
              {cat}
            </button>
          ))}
        </div>

        {loading
          ? <div style={{ textAlign: 'center', padding: 60 }}><Spinner size={32} /></div>
          : (
            <div className="product-grid">
              {display.map((p, i) => (
                <ProductCard key={p.id} product={p} index={i} onClick={onSelectProduct} />
              ))}
            </div>
          )}
      </div>
    </section>
  );
}

// ──────────────────────────────────────────────────────────────
//  PRODUCT DETAIL MODAL
// ──────────────────────────────────────────────────────────────
function ProductModal({ product, onClose, onOrder }) {
  const [imgIdx, setImgIdx] = useState(0);
  const [lightbox, setLightbox] = useState(false);
  const gallery = useMemo(() => {
    if (!product) return [];
    const g = typeof product.gallery === 'string' ? JSON.parse(product.gallery || '[]') : (product.gallery || []);
    return g.length ? g : [{ url: product.image_url, label: 'Main' }];
  }, [product]);

  useEffect(() => { setImgIdx(0); setLightbox(false); }, [product]);

  // Escape key closes lightbox
  useEffect(() => {
    if (!lightbox) return;
    const handler = (e) => { if (e.key === 'Escape') setLightbox(false); };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [lightbox]);

  // ── Dynamic Product Schema injection for Google rich results ──
  useEffect(() => {
    if (!product) return;
    const slug = product.name
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-|-$/g, '');
    const productUrl = 'https://aurellebride.com/collection#' + slug;
    const images = gallery.map(function(g) { return g.url; }).filter(Boolean);

    const schema = {
      "@context": "https://schema.org",
      "@type":    "Product",
      "name":     product.name,
      "description": product.desc || (product.name + ' — luxury bridal couture by Aurelle Bride. Made to your measurements, shipped worldwide.'),
      "image":    images.length ? images : [product.image_url],
      "brand":    { "@type": "Brand", "name": "Aurelle Bride" },
      "sku":      'AB-' + product.id,
      "category": product.col || "Bridal Couture",
      "url":      productUrl,
      "offers": {
        "@type":         "Offer",
        "priceCurrency": "PKR",
        "price":         String(product.priceValue || 0),
        "availability":  product.status === 'AVAILABLE'
                           ? "https://schema.org/InStock"
                           : "https://schema.org/LimitedAvailability",
        "itemCondition": "https://schema.org/NewCondition",
        "seller":        { "@type": "Organization", "name": "Aurelle Bride" },
        "url":           productUrl
      }
    };

    var existing = document.getElementById('product-schema-dynamic');
    if (existing) existing.remove();
    var el = document.createElement('script');
    el.type = 'application/ld+json';
    el.id   = 'product-schema-dynamic';
    el.text = JSON.stringify(schema);
    document.head.appendChild(el);

    var prevTitle = document.title;
    document.title = product.name + ' — Aurelle Bride';

    return function() {
      var s = document.getElementById('product-schema-dynamic');
      if (s) s.remove();
      document.title = prevTitle;
    };
  }, [product]);

  if (!product) return null;

  const wa = (brand.whatsapp || '').replace(/\D/g, '');
  const waMsg = encodeURIComponent(`Hi! I'm interested in: ${product.name} (₨ ${Number(product.priceValue).toLocaleString()} PKR)`);

  return (
    <>
    {/* ── Lightbox ── */}
    {lightbox && (
      <div
        onClick={() => setLightbox(false)}
        style={{
          position: 'fixed', inset: 0, zIndex: 99999,
          background: 'rgba(0,0,0,0.92)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'zoom-out',
        }}
      >
        {/* Close button */}
        <button
          onClick={() => setLightbox(false)}
          style={{
            position: 'absolute', top: 18, right: 22, background: 'none',
            border: 'none', color: '#fff', fontSize: 28, cursor: 'pointer',
            lineHeight: 1, zIndex: 2, opacity: 0.8,
          }}
          aria-label="Close zoom"
        >✕</button>

        {/* Prev / Next arrows */}
        {gallery.length > 1 && (
          <>
            <button onClick={e => { e.stopPropagation(); setImgIdx(i => (i - 1 + gallery.length) % gallery.length); }}
              style={{
                position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)',
                background: 'rgba(255,255,255,0.12)', border: 'none', borderRadius: '50%',
                width: 44, height: 44, fontSize: 20, color: '#fff', cursor: 'pointer', zIndex: 2,
              }}>‹</button>
            <button onClick={e => { e.stopPropagation(); setImgIdx(i => (i + 1) % gallery.length); }}
              style={{
                position: 'absolute', right: 16, top: '50%', transform: 'translateY(-50%)',
                background: 'rgba(255,255,255,0.12)', border: 'none', borderRadius: '50%',
                width: 44, height: 44, fontSize: 20, color: '#fff', cursor: 'pointer', zIndex: 2,
              }}>›</button>
          </>
        )}

        {/* Full image */}
        <img
          src={gallery[imgIdx]?.url}
          alt={gallery[imgIdx]?.label || product.name}
          onClick={e => e.stopPropagation()}
          style={{
            maxWidth: '92vw', maxHeight: '92vh',
            objectFit: 'contain', borderRadius: 4,
            boxShadow: '0 8px 48px rgba(0,0,0,0.6)',
            cursor: 'default',
          }}
        />

        {/* Caption */}
        {gallery[imgIdx]?.label && (
          <div style={{
            position: 'absolute', bottom: 20, left: '50%', transform: 'translateX(-50%)',
            background: 'rgba(0,0,0,0.6)', color: '#fff', padding: '6px 16px',
            borderRadius: 20, fontSize: 13, letterSpacing: '.04em',
          }}>{gallery[imgIdx].label}</div>
        )}
      </div>
    )}

    <div className="modal-bg" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal-card" style={{ maxWidth: 860, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0, padding: 0, overflow: 'hidden' }}>
        <style>{`@media(max-width:680px){.prod-modal-grid{grid-template-columns:1fr!important}}`}</style>

        {/* Gallery */}
        <div className="prod-modal-grid" style={{ background: 'var(--bg-3)', position: 'relative' }}>
          <div style={{ aspectRatio: '3/4', position: 'relative', overflow: 'hidden' }}>
            <img src={gallery[imgIdx]?.url} alt={gallery[imgIdx]?.label || product.name}
              onClick={() => setLightbox(true)}
              style={{ width: '100%', height: '100%', objectFit: 'cover', cursor: 'zoom-in' }} />
            {/* Zoom hint */}
            <div onClick={() => setLightbox(true)} style={{
              position: 'absolute', bottom: 10, right: 10, cursor: 'zoom-in',
              background: 'rgba(0,0,0,0.55)', borderRadius: 6, padding: '4px 8px',
              fontSize: 11, color: '#fff', letterSpacing: '.06em', userSelect: 'none',
            }}>🔍 tap to zoom</div>
            <div style={{ position: 'absolute', top: 14, left: 14 }}>
              <span className="badge">{product.status}</span>
            </div>
          </div>
          {gallery.length > 1 && (
            <div style={{ display: 'flex', gap: 8, padding: '12px 16px', overflowX: 'auto' }}>
              {gallery.map((img, i) => (
                <button key={i} onClick={() => setImgIdx(i)}
                  style={{ width: 56, height: 72, border: `2px solid ${i === imgIdx ? 'var(--gold)' : 'var(--line)'}`, borderRadius: 6, overflow: 'hidden', cursor: 'pointer', flexShrink: 0, padding: 0 }}>
                  <img src={img.url} alt={img.label || ''} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Info */}
        <div style={{ padding: 32, overflowY: 'auto', maxHeight: '85vh', display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <span className="eyebrow" style={{ marginBottom: 8, display: 'block' }}>{product.col}</span>
              <h2 style={{ fontFamily: 'var(--serif)', fontSize: 28, fontWeight: 400, marginBottom: 8 }}>{product.name}</h2>
              <PriceDisplay pkr={product.priceValue}
                style={{ fontFamily: 'var(--serif)', fontSize: 22, color: 'var(--gold)', fontStyle: 'italic', display: 'block' }}
                showPkrSub={true}
              />
            </div>
            <button className="icon-btn" onClick={onClose} aria-label="Close">✕</button>
          </div>

          {product.desc && <p style={{ color: 'var(--ink-2)', lineHeight: 1.65 }}>{product.desc}</p>}

          {product.fabric_detail && (
            <div style={{ borderTop: '1px solid var(--line)', paddingTop: 16 }}>
              <div className="eyebrow" style={{ marginBottom: 8 }}>Fabric & Craft</div>
              <p style={{ color: 'var(--ink-2)', fontSize: 14 }}>{product.fabric_detail}</p>
            </div>
          )}

          {/* Details grid */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {product.delivery_weeks && (
              <div style={{ padding: '12px 14px', background: 'var(--surface-2)', borderRadius: 8, border: '1px solid var(--line)' }}>
                <div className="eyebrow" style={{ fontSize: 9, marginBottom: 4 }}>Delivery</div>
                <div style={{ fontSize: 14, color: 'var(--ink)' }}>~{product.delivery_weeks} weeks</div>
              </div>
            )}
            <div style={{ padding: '12px 14px', background: 'var(--surface-2)', borderRadius: 8, border: '1px solid var(--line)' }}>
              <div className="eyebrow" style={{ fontSize: 9, marginBottom: 4 }}>Sizing</div>
              <div style={{ fontSize: 14, color: 'var(--ink)' }}>Made to measure</div>
            </div>
          </div>

          {/* Shipping — always inquire, never fixed fee */}
          <ShippingNote />

          {product.care && (
            <div style={{ padding: '10px 14px', borderRadius: 8, background: 'var(--bg-2)', border: '1px solid var(--line)' }}>
              <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Care: </span>
              <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>{product.care}</span>
            </div>
          )}

          <div style={{ padding: '14px', borderRadius: 10, background: 'var(--gold-soft)', border: '1px solid color-mix(in oklab, var(--gold) 20%, transparent)' }}>
            <p style={{ fontSize: 13, color: 'var(--gold)', fontFamily: 'var(--mono)', letterSpacing: '.1em', textTransform: 'uppercase', marginBottom: 6 }}>Made to your measurements</p>
            <p style={{ fontSize: 13, color: 'var(--ink-2)' }}>Every garment is stitched fresh. We collect your measurements before production begins.</p>
          </div>

          <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
            <button className="btn btn-primary" style={{ flex: 1 }}
              onClick={() => { onClose(); onOrder(product); }}>
              Order / Enquire
            </button>
            <a className="btn btn-ghost" href={`https://wa.me/${wa}?text=${waMsg}`}
              target="_blank" rel="noopener noreferrer" aria-label="WhatsApp">
              <svg width="16" height="16" fill="currentColor" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413z"/></svg>
              WhatsApp
            </a>
          </div>
        </div>
      </div>
    </div>
    </>
  );
}

// ──────────────────────────────────────────────────────────────
//  CUSTOM ORDER — multi-step form
// ──────────────────────────────────────────────────────────────
// ── Helper sub-components for Custom Order ────────────────────
function OrderStep({ n, t, children }) {
  return (
    <div style={{ marginBottom: 32 }}>
      <div className="eyebrow" style={{ marginBottom: 14 }}><span className="dot" />STEP {n} · {t}</div>
      {children}
    </div>
  );
}

function OrderTile({ active, onClick, children, sub, img }) {
  return (
    <button type="button" onClick={onClick} className="card"
      style={{ padding: img ? 10 : '18px 16px', textAlign: 'left',
        borderColor: active ? 'var(--gold)' : 'var(--line)',
        background: active ? 'var(--gold-soft)' : 'var(--surface)',
        color: active ? 'var(--gold)' : 'var(--ink)',
        cursor: 'pointer', transition: 'all .2s' }}>
      {img && (
        <div style={{ aspectRatio: '1', borderRadius: 'var(--rad)', overflow: 'hidden', marginBottom: 8, background: '#faf8f3' }}>
          <img src={img} alt="" loading="lazy"
            onError={e => { e.target.style.display = 'none'; }}
            style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block', padding: 8 }} />
        </div>
      )}
      <div style={{ fontWeight: 500, fontSize: 13 }}>{children}</div>
      {sub && <div style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '.18em', color: active ? 'var(--gold)' : 'var(--ink-3)', marginTop: 3 }}>{sub}</div>}
    </button>
  );
}

// ──────────────────────────────────────────────────────────────
//  CUSTOM ORDER — original visual builder with sticky summary
// ──────────────────────────────────────────────────────────────
function CustomOrderSection({ preProduct, onSuccess }) {
  const { toast, show } = useToast();
  const { convert, currency, rate } = useCurrency();

  const [type, setType]         = useState('lehenga');
  const [palette, setPalette]   = useState('classic');
  const [fabric, setFabric]     = useState('silk');
  const [embs, setEmbs]         = useState([]);
  const [neckline, setNeckline] = useState('sweetheart');
  const [sleeves, setSleeves]   = useState('full');
  const [files, setFiles]       = useState([]);
  const [contact, setContact]   = useState({ name: '', email: '', phone: '', phone_whatsapp: true, notes: '', occasion: 'walima' });
  const [submitting, setSubmitting] = useState(false);

  // Measurements
  const [measurements, setMeasurements] = useState({ unit: 'cm', bust:'', waist:'', hips:'', height:'', shoulder:'', sleeve_length:'', shirt_length:'', trouser_length:'', measurement_note:'regular', skip: false });

  const types = [
    { id: 'lehenga',  label: 'Lehenga',     img: '/uploads/silhouettes/lehenga.jpg' },
    { id: 'sharara',  label: 'Sharara',     img: '/uploads/silhouettes/sharara.jpg' },
    { id: 'gharara',  label: 'Gharara',     img: '/uploads/silhouettes/gharara.jpg' },
    { id: 'anarkali', label: 'Anarkali',    img: '/uploads/silhouettes/anarkali.jpg' },
    { id: 'gown',     label: 'Bridal Gown', img: '/uploads/silhouettes/gown.jpg' },
    { id: 'mexi',     label: 'Bridal Mexi', img: '/uploads/silhouettes/mexi.jpg' },
  ];

  // Map product col → garment type id when coming from product modal
  const COL_TO_TYPE = {
    'lehenga': 'lehenga', 'sharara': 'sharara', 'gharara': 'gharara',
    'anarkali': 'anarkali', 'bridal gown': 'gown', 'gown': 'gown',
    'bridal mexi': 'mexi', 'mexi': 'mexi',
  };
  useEffect(() => {
    if (!preProduct) return;
    const col = (preProduct.col || preProduct.garment_type || '').toLowerCase().trim();
    const matched = COL_TO_TYPE[col];
    if (matched) setType(matched);
    // Pre-fill name/email if product has a customer field (unlikely but safe)
  }, [preProduct]);
  const palettes = [
    { id: 'classic', name: 'Classic Bridal',  c: ['#8B0000','#FFD700','#FFFFFF','#C9A961'] },
    { id: 'royal',   name: 'Royal Sapphire',  c: ['#0a2240','#3556a8','#C0C0C0','#E6E6FA'] },
    { id: 'sunset',  name: 'Golden Hour',     c: ['#a9772a','#d3a35b','#f3d8a0','#FFF8DC'] },
    { id: 'emerald', name: 'Emerald Garden',  c: ['#0f4d3a','#1f8060','#9bc7a3','#ecf3e0'] },
    { id: 'rose',    name: 'Rose Atelier',    c: ['#7a2030','#c47083','#e9c3c8','#fff4f1'] },
    { id: 'onyx',    name: 'Onyx Luxe',       c: ['#0E0E10','#3A3A3F','#777','#C9A961']   },
  ];
  const fabricList = [
    { id: 'silk',      label: 'Silk',      price: 25000 },
    { id: 'velvet',    label: 'Velvet',    price: 35000 },
    { id: 'georgette', label: 'Georgette', price: 18000 },
    { id: 'organza',   label: 'Organza',   price: 22000 },
    { id: 'net',       label: 'Net',       price: 15000 },
    { id: 'brocade',   label: 'Brocade',   price: 42000 },
  ];
  const embOpts = [
    { id: 'zari',   label: 'Zari Work',         price: 15000 },
    { id: 'mirror', label: 'Mirror Work',       price: 12000 },
    { id: 'thread', label: 'Thread Embroidery', price: 18000 },
    { id: 'stone',  label: 'Stone Work',        price: 22000 },
    { id: 'pearl',  label: 'Pearl Beading',     price: 14000 },
    { id: 'gota',   label: 'Gota Patti',        price: 11000 },
  ];
  const necklines  = [['sweetheart','Sweetheart'],['vneck','V-Neck'],['boat','Boat'],['scoop','Scoop'],['halter','Halter']];
  const sleeveOpts = [['full','Full'],['threequarter','¾'],['cap','Cap'],['sleeveless','Sleeveless']];
  const basePrices = { lehenga:150000, sharara:120000, gharara:110000, anarkali:95000, gown:135000, mexi:115000 };

  const breakdown = useMemo(() => {
    const b = basePrices[type] || 0;
    const f = fabricList.find(x => x.id === fabric)?.price || 0;
    const e = embs.reduce((s, id) => s + (embOpts.find(o => o.id === id)?.price || 0), 0);
    return { base: b, fabric: f, embs: e, total: b + f + e };
  }, [type, fabric, embs]);

  // Show price in detected currency
  const showPrice = (pkr) => {
    if (!rate || currency === 'PKR') return '₨ ' + Number(pkr).toLocaleString();
    return convert(pkr) || ('₨ ' + Number(pkr).toLocaleString());
  };

  const onUpload = (e) => {
    const list = Array.from(e.target.files || []);
    if (files.length + list.length > 8) { show('Max 8 files', 'error'); return; }
    setFiles(prev => [...prev, ...list.map(f => ({
      name: f.name,
      size: (f.size / 1024 / 1024).toFixed(2) + ' MB',
      url:  f.type.startsWith('image/') ? URL.createObjectURL(f) : null,
      _raw: f,
    }))]);
  };

  const submit = async () => {
    if (!contact.name || !contact.email) { show('Please share your name and email', 'error'); return; }
    if (!contact.phone) { show('Please add your phone number so we can reach you', 'error'); return; }
    setSubmitting(true);
    const payload = {
      name: contact.name, email: contact.email, phone: contact.phone, phone_whatsapp: contact.phone_whatsapp, occasion: contact.occasion, notes: contact.notes,
      garment_type: type, palette, fabric, embellishments: embs.join(','), neckline, sleeves,
      total_estimate: breakdown.total,
      summary: `${type} · ${palette} · ${fabric} · ${embs.length} emb.`,
      // measurements
      unit: measurements.unit, bust: measurements.bust, waist: measurements.waist,
      hips: measurements.hips, height: measurements.height, shoulder: measurements.shoulder,
      sleeve_length: measurements.sleeve_length, shirt_length: measurements.shirt_length,
      trouser_length: measurements.trouser_length, measurement_note: measurements.measurement_note,
    };
    try {
      const recaptchaToken = await getRecaptchaToken('custom_order');
      const r = await fetch('/api/customs.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...payload, recaptcha_token: recaptchaToken }) });
      if (!r.ok) throw new Error();
      const { id } = await r.json();
      if (files.length) {
        const fd = new FormData();
        files.forEach(f => f._raw && fd.append('files[]', f._raw));
        fd.append('parent_table', 'customs');
        fd.append('parent_id', id);
        await fetch('/api/upload.php', { method: 'POST', body: fd });
      }
      show("Brief received — we'll email you within 24 hours.", 'success');
      setContact({ name: '', email: '', notes: '', occasion: 'walima' });
      setFiles([]); setEmbs([]);
    } catch { show('Could not submit. Please try again.', 'error'); }
    finally { setSubmitting(false); }
  };

  return (
    <section className="section" aria-labelledby="custom-heading">
      <div className="container">
        <div style={{ textAlign: 'center', maxWidth: 720, margin: '0 auto 60px' }}>
          <div className="eyebrow"><span className="dot" />THE BUILDER</div>
          <h1 id="custom-heading" style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(44px,5vw,72px)', marginTop: 18, lineHeight: 1.05 }}>
            Design your <em style={{ color: 'var(--gold)', fontStyle: 'italic' }}>dream.</em>
          </h1>
          <p style={{ color: 'var(--ink-2)', marginTop: 18 }}>Build a brief in steps. Attach inspiration. We respond within 24 hours.</p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 48 }}>
          <style>{`@media(max-width:860px){.custom-grid{grid-template-columns:1fr!important}.custom-aside{position:static!important}}`}</style>
          <div className="custom-grid" style={{ display: 'contents' }}>

          <div>
            {/* Step 01 — Silhouette */}
            <OrderStep n="01" t="SILHOUETTE">
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
                {types.map(o => (
                  <OrderTile key={o.id} active={type === o.id} onClick={() => setType(o.id)} img={o.img} sub={`base ${showPrice(basePrices[o.id])}`}>
                    {o.label}
                  </OrderTile>
                ))}
              </div>
            </OrderStep>

            {/* Step 02 — Palette */}
            <OrderStep n="02" t="PALETTE">
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
                {palettes.map(p => (
                  <button type="button" key={p.id} onClick={() => setPalette(p.id)} className="card"
                    style={{ padding: 14, textAlign: 'left', borderColor: palette === p.id ? 'var(--gold)' : 'var(--line)', cursor: 'pointer' }}>
                    <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
                      {p.c.map(c => <span key={c} style={{ width: 20, height: 32, borderRadius: 3, background: c, border: '1px solid var(--line)' }} />)}
                    </div>
                    <div style={{ fontSize: 12, fontWeight: 500, color: palette === p.id ? 'var(--gold)' : 'var(--ink)' }}>{p.name}</div>
                  </button>
                ))}
              </div>
            </OrderStep>

            {/* Step 03 — Fabric */}
            <OrderStep n="03" t="FABRIC">
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
                {fabricList.map(f => (
                  <OrderTile key={f.id} active={fabric === f.id} onClick={() => setFabric(f.id)} sub={`+${showPrice(f.price)}`}>
                    {f.label}
                  </OrderTile>
                ))}
              </div>
            </OrderStep>

            {/* Step 04 — Details */}
            <OrderStep n="04" t="SILHOUETTE DETAILS">
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 8, fontFamily: 'var(--mono)', letterSpacing: '.18em' }}>NECKLINE</div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                    {necklines.map(([id, l]) => <OrderTile key={id} active={neckline === id} onClick={() => setNeckline(id)}>{l}</OrderTile>)}
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 8, fontFamily: 'var(--mono)', letterSpacing: '.18em' }}>SLEEVES</div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                    {sleeveOpts.map(([id, l]) => <OrderTile key={id} active={sleeves === id} onClick={() => setSleeves(id)}>{l}</OrderTile>)}
                  </div>
                </div>
              </div>
            </OrderStep>

            {/* Step 05 — Embellishments */}
            <OrderStep n="05" t="EMBELLISHMENTS">
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {embOpts.map(o => (
                  <label key={o.id} className="card"
                    style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 18px', cursor: 'pointer' }}>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                      <input type="checkbox" checked={embs.includes(o.id)}
                        style={{ width: 18, height: 18, accentColor: 'var(--gold)' }}
                        onChange={() => setEmbs(prev => prev.includes(o.id) ? prev.filter(x => x !== o.id) : [...prev, o.id])} />
                      <span style={{ fontSize: 14 }}>{o.label}</span>
                    </span>
                    <span style={{ color: 'var(--gold)', fontFamily: 'var(--mono)', fontSize: 12 }}>+{showPrice(o.price)}</span>
                  </label>
                ))}
              </div>
            </OrderStep>

            {/* Step 06 — Measurements */}
            <OrderStep n="06" t="YOUR MEASUREMENTS">
              <MeasurementsForm value={measurements} onChange={setMeasurements} />
            </OrderStep>

            {/* Step 07 — Inspiration upload */}
            <OrderStep n="07" t="INSPIRATION (OPTIONAL)">
              <label className="card" style={{ padding: 30, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10, borderStyle: 'dashed', cursor: 'pointer' }}>
                <svg width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24"><path d="M12 16V4M7 9l5-5 5 5"/><path d="M5 16v3a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3"/></svg>
                <div style={{ fontSize: 14 }}>Drop or click to upload references</div>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '.18em', color: 'var(--ink-3)' }}>JPG · PNG · PDF · MAX 8 FILES</div>
                <input type="file" multiple accept="image/*,application/pdf" onChange={onUpload} style={{ display: 'none' }} />
              </label>
              {files.length > 0 && (
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10, marginTop: 14 }}>
                  {files.map((f, i) => (
                    <div key={i} className="card" style={{ aspectRatio: '1', overflow: 'hidden', position: 'relative' }}>
                      {f.url ? <img src={f.url} style={{ width: '100%', height: '100%', objectFit: 'cover' }} alt="" /> : <div style={{ padding: 14, fontSize: 11 }}>{f.name}</div>}
                      <button className="icon-btn" onClick={() => setFiles(prev => prev.filter((_, j) => j !== i))}
                        style={{ position: 'absolute', top: 6, right: 6, width: 28, height: 28, background: 'rgba(0,0,0,.6)', color: '#fff', border: 'none' }}>✕</button>
                    </div>
                  ))}
                </div>
              )}
            </OrderStep>

            {/* Step 08 — Your details */}
            <OrderStep n="08" t="YOUR DETAILS">
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <Field label="Full name" required>
                  <input className="input" value={contact.name} onChange={e => setContact({ ...contact, name: e.target.value })} />
                </Field>
                <Field label="Email" required>
                  <input className="input" type="email" value={contact.email} onChange={e => setContact({ ...contact, email: e.target.value })} />
                </Field>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 14 }}>
                <PhoneInput label="Phone Number" required
                  onChange={(full) => setContact({ ...contact, phone: full })} />
                <Field label="Available on WhatsApp?">
                  <label style={{ display:'flex', alignItems:'center', gap:10, cursor:'pointer', height:42, fontSize:14 }}>
                    <input type="checkbox" checked={contact.phone_whatsapp}
                      onChange={e => setContact({ ...contact, phone_whatsapp: e.target.checked })}
                      style={{ width:18, height:18, accentColor:'var(--gold)' }} />
                    <span>Yes, this number is on WhatsApp</span>
                  </label>
                </Field>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 14 }}>
                <Field label="Occasion">
                  <select className="select" value={contact.occasion} onChange={e => setContact({ ...contact, occasion: e.target.value })}>
                    {['barat','walima','mehndi','nikkah','engagement','other'].map(o => (
                      <option key={o} value={o}>{o.charAt(0).toUpperCase() + o.slice(1)}</option>
                    ))}
                  </select>
                </Field>
                <Field label="Event date (optional)">
                  <input className="input" type="date" />
                </Field>
                <Field style={{ gridColumn: '1 / -1' }} label="Notes (sizing, references, must-haves)">
                  <textarea className="textarea" rows="4" value={contact.notes}
                    onChange={e => setContact({ ...contact, notes: e.target.value })}
                    placeholder="E.g. I'd love something between Royal Sapphire and Onyx, with hand-couched gold dabka…" />
                </Field>
              </div>
            </OrderStep>
          </div>

          {/* Sticky summary sidebar */}
          <aside className="custom-aside" style={{ position: 'sticky', top: 100, height: 'fit-content' }}>
            <div className="card" style={{ padding: 30 }}>
              <div className="eyebrow"><span className="dot" />YOUR BRIEF</div>
              <h3 style={{ fontFamily: 'var(--serif)', fontSize: 28, marginTop: 14, marginBottom: 24 }}>Design preview</h3>
              <div style={{ aspectRatio: '3/4', borderRadius: 'var(--rad)', overflow: 'hidden', border: '1px solid var(--line)', marginBottom: 20, position: 'relative', background: '#faf8f3' }}>
                {types.find(x => x.id === type)?.img
                  ? <img src={types.find(x => x.id === type).img} alt={types.find(x => x.id === type).label}
                      onError={e => { e.target.style.display = 'none'; }}
                      style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block', padding: 16 }} />
                  : <div style={{ width: '100%', height: '100%', background: 'var(--bg-3)' }} />}
                <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '18px 20px', background: 'linear-gradient(to top, rgba(14,14,16,.9), transparent)', color: '#fff' }}>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '.22em', color: 'var(--gold)' }}>
                    {palettes.find(p => p.id === palette)?.name?.toUpperCase()}
                  </div>
                  <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 22, marginTop: 4 }}>
                    {types.find(t => t.id === type)?.label}
                  </div>
                </div>
              </div>

              {/* Price breakdown */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12, fontSize: 13 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ color: 'var(--ink-3)' }}>Base ({type})</span>
                  <span>{showPrice(breakdown.base)}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ color: 'var(--ink-3)' }}>Fabric ({fabric})</span>
                  <span>+{showPrice(breakdown.fabric)}</span>
                </div>
                {breakdown.embs > 0 && (
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: 'var(--ink-3)' }}>Embellishments × {embs.length}</span>
                    <span>+{showPrice(breakdown.embs)}</span>
                  </div>
                )}
                <div className="hairline" />
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.18em', color: 'var(--ink-3)' }}>ESTIMATE</span>
                  <span style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 28, color: 'var(--gold)' }}>{showPrice(breakdown.total)}</span>
                </div>
                {currency !== 'PKR' && (
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--mono)', letterSpacing: '.1em' }}>
                    ₨ {Number(breakdown.total).toLocaleString()} PKR · approx. {currency}
                  </div>
                )}
              </div>

              <ShippingNote compact style={{ marginTop: 12 }} />

              <button className="btn btn-primary btn-lg"
                style={{ width: '100%', justifyContent: 'center', marginTop: 24 }}
                onClick={submit} disabled={submitting}>
                {submitting ? <Spinner size={16} /> : 'Submit brief'}
              </button>
              <p style={{ fontSize: 11, color: 'var(--ink-3)', textAlign: 'center', marginTop: 12, fontFamily: 'var(--mono)', letterSpacing: '.12em' }}>
                WE REPLY WITHIN 24H · NO COMMITMENT
              </p>
            </div>
          </aside>
          </div>
        </div>
      </div>
      <Toast toast={toast} />
    </section>
  );
}

// ──────────────────────────────────────────────────────────────
//  JOURNAL / BLOG
// ──────────────────────────────────────────────────────────────
function JournalSection({ limit = 3 }) {
  const [posts, setPosts] = useState([]);
  const sectionRef = useRef(null);
  useReveal(sectionRef);

  useEffect(() => {
    fetch(`/api/posts.php?status=published&limit=${limit}`)
      .then(r => r.json())
      .then(d => { if (Array.isArray(d) && d.length) setPosts(d); })
      .catch(() => {});
  }, [limit]);

  if (!posts.length) return null;

  return (
    <section className="section" ref={sectionRef} aria-labelledby="journal-heading">
      <div className="container">
        <div className="section-head reveal">
          <div>
            <span className="eyebrow" style={{ marginBottom: 12, display: 'block' }}><span className="dot" />Journal</span>
            <h2 id="journal-heading">From the atelier</h2>
          </div>
        </div>
        <div className="grid-3">
          {posts.map((post, i) => (
            <article key={post.id} className="card reveal" style={{ animationDelay: `${i * 80}ms`, overflow: 'hidden', cursor: 'pointer' }}>
              {post.cover_url && (
                <div style={{ aspectRatio: '16/9', overflow: 'hidden' }}>
                  <img src={post.cover_url} alt={post.cover_alt || post.title}
                    style={{ width: '100%', height: '100%', objectFit: 'cover', transition: 'transform .6s var(--ease-out)' }}
                    loading="lazy" />
                </div>
              )}
              <div style={{ padding: '20px 22px 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                  <span className="badge">{post.tag}</span>
                  {post.reading_time && (
                    <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-3)', letterSpacing: '.14em' }}>{post.reading_time} MIN READ</span>
                  )}
                </div>
                <h3 style={{ fontFamily: 'var(--serif)', fontSize: 20, fontWeight: 400, lineHeight: 1.3 }}>{post.title}</h3>
                {post.excerpt && <p style={{ color: 'var(--ink-3)', fontSize: 13, lineHeight: 1.6 }}>{post.excerpt}</p>}
                <div style={{ marginTop: 4, color: 'var(--ink-3)', fontSize: 12, fontFamily: 'var(--mono)' }}>{formatDate(post.date)}</div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

// ──────────────────────────────────────────────────────────────
//  REVIEWS
// ──────────────────────────────────────────────────────────────
function ReviewsSection() {
  const [reviews, setReviews] = useState(SEED_REVIEWS);
  const [showForm, setShowForm] = useState(false);
  const sectionRef = useRef(null);
  useReveal(sectionRef);

  useEffect(() => {
    fetch('/api/reviews.php?featured=1&status=approved')
      .then(r => r.json())
      .then(d => { if (Array.isArray(d) && d.length) setReviews(d); })
      .catch(() => {});
  }, []);

  return (
    <section className="section" ref={sectionRef} style={{ background: 'var(--bg-2)', borderBlock: '1px solid var(--line)' }} aria-labelledby="reviews-heading">
      <div className="container">
        <div className="section-head reveal">
          <div>
            <span className="eyebrow" style={{ marginBottom: 12, display: 'block' }}><span className="dot" />Brides</span>
            <h2 id="reviews-heading">Real brides, real stories</h2>
          </div>
          <button className="btn btn-ghost" onClick={() => setShowForm(true)}>Share your experience →</button>
        </div>
        <div className="grid-3">
          {reviews.map((r, i) => (
            <div key={r.id} className="reveal" style={{ animationDelay: `${i * 80}ms` }}>
              <ReviewCard review={r} />
            </div>
          ))}
        </div>
      </div>
      {showForm && <ReviewFormModal onClose={() => setShowForm(false)} />}
    </section>
  );
}

function ReviewFormModal({ onClose }) {
  const [form, setForm] = useState({ name: '', email: '', phone: '', location: '', occasion: '', rating: 5, title: '', body: '' });
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState(false);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = async () => {
    if (!form.name || !form.email || !form.body) return;
    setSubmitting(true);
    try {
      const recaptchaToken = await getRecaptchaToken('review');
      await apiFetch('/reviews', { method: 'POST', body: JSON.stringify({ ...form, recaptcha_token: recaptchaToken }) });
      setDone(true);
    } catch {
      alert('Something went wrong. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal open onClose={onClose} title="Share your experience">
      {done ? (
        <div style={{ textAlign: 'center', padding: '24px 0' }}>
          <div style={{ fontSize: 48, marginBottom: 16 }}>✨</div>
          <h3 style={{ fontFamily: 'var(--serif)', fontSize: 24, marginBottom: 12 }}>Thank you!</h3>
          <p style={{ color: 'var(--ink-2)' }}>Your review has been submitted and will appear once approved by our team.</p>
          <button className="btn btn-ghost" style={{ marginTop: 24 }} onClick={onClose}>Close</button>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="grid-2">
            <Field label="Your Name" required>
              <input className="input" placeholder="Amna R." value={form.name} onChange={e => set('name', e.target.value)} />
            </Field>
            <Field label="Email" required hint="not shown publicly">
              <input className="input" type="email" placeholder="amna@email.com" value={form.email} onChange={e => set('email', e.target.value)} />
            </Field>
          </div>
          <PhoneInput label="Phone (optional — for verification)"
            onChange={(full) => set('phone', full)} />
          <div className="grid-2">
            <Field label="Location" hint="shown publicly">
              <input className="input" placeholder="Dubai, UAE" value={form.location} onChange={e => set('location', e.target.value)} />
            </Field>
            <Field label="Occasion">
              <input className="input" placeholder="Wedding · Nov 2025" value={form.occasion} onChange={e => set('occasion', e.target.value)} />
            </Field>
          </div>
          <Field label="Rating">
            <StarRating value={form.rating} onChange={v => set('rating', v)} size={28} />
          </Field>
          <Field label="Title">
            <input className="input" placeholder="A short headline for your review" value={form.title} onChange={e => set('title', e.target.value)} />
          </Field>
          <Field label="Your Review" required>
            <textarea className="textarea" placeholder="Tell us about your experience with Aurelle Bride…"
              value={form.body} onChange={e => set('body', e.target.value)} />
          </Field>
          <p style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: -6 }}>Your review will be visible after approval by our team, typically within 48 hours.</p>
          <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end' }}>
            <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
            <button className="btn btn-primary" onClick={handleSubmit} disabled={submitting || !form.name || !form.body}>
              {submitting ? <Spinner size={14} /> : null}
              {submitting ? 'Submitting…' : 'Submit Review'}
            </button>
          </div>
        </div>
      )}
    </Modal>
  );
}

// ──────────────────────────────────────────────────────────────
//  FOOTER
// ──────────────────────────────────────────────────────────────
function SiteFooter({ setPage }) {
  const [email, setEmail] = useState('');
  const [subbed, setSubbed] = useState(false);

  const handleSub = async () => {
    if (!email.match(/^\S+@\S+\.\S+$/)) return;

    try {
      const recaptchaToken = await getRecaptchaToken('newsletter');
      await fetch('/api/newsletter.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, recaptcha_token: recaptchaToken })
      });
    } catch {}

    setSubbed(true);
  };

  const navLinks = {
    collection: [
      { label: 'Lehenga',     path: '/collection', col: 'Lehenga' },
      { label: 'Sharara',     path: '/collection', col: 'Sharara' },
      { label: 'Gharara',     path: '/collection', col: 'Gharara' },
      { label: 'Anarkali',    path: '/collection', col: 'Anarkali' },
      { label: 'Bridal Mexi', path: '/collection', col: 'Bridal Mexi' },
      { label: 'Gown',        path: '/collection', col: 'Gown' }
    ],
    atelier: [
      { label: 'Custom Order', key: 'custom', path: '/custom' },
      { label: 'Journal', key: 'journal', path: '/journal' },
      { label: 'Contact', key: 'contact', path: '/contact' }
    ]
  };

  const handleNav = (e, pageKey) => {
    e.preventDefault();
    if (pageKey) setPage(pageKey);
  };

  return (
    <footer className="site" role="contentinfo">
      <div className="container">
        <div className="footcols">
          {/* Brand */}
          <div>
            <a
              href="/"
              onClick={(e) => {
                e.preventDefault();
                setPage('home');
              }}
              style={{
                marginBottom: 20,
                display: 'flex',
                alignItems: 'center',
                gap: '14px',
                textDecoration: 'none'
              }}
              aria-label="Aurelle Bride homepage"
            >
              <img
                src="/assets/logo/aurelle-logo.png"
                alt="Aurelle Bride"
                style={{
                  height: '64px',
                  width: 'auto',
                  display: 'block'
                }}
              />

              <span
                style={{
                  fontFamily: 'var(--serif)',
                  fontSize: '34px',
                  fontWeight: 500,
                  color: 'var(--ink)',
                  letterSpacing: '.04em'
                }}
              >
                Aurelle Bride
              </span>
            </a>

            <p
              style={{
                color: 'var(--ink-3)',
                fontSize: 14,
                lineHeight: 1.65,
                marginBottom: 20,
                maxWidth: '30ch'
              }}
            >
              A future-forward bridal atelier. One-of-one couture,
              made to your measurements. Shipped worldwide.
            </p>

            {!subbed ? (
              <div style={{ display: 'flex', gap: 8 }}>
                <input
                  className="input"
                  style={{ width: 'auto', flex: 1 }}
                  type="email"
                  placeholder="Your email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  aria-label="Newsletter email"
                />
                <button
                  className="btn btn-primary btn-sm"
                  onClick={handleSub}
                >
                  Subscribe
                </button>
              </div>
            ) : (
              <p
                style={{
                  color: 'var(--gold)',
                  fontSize: 13,
                  fontFamily: 'var(--mono)'
                }}
              >
                ✓ You're on the list
              </p>
            )}
          </div>

          {/* Collection */}
          <div>
            <h5>Collection</h5>
            <ul>
              {navLinks.collection.map((item) => (
                <li key={item.label}>
                  <a
                    href={item.path}
                    onClick={(e) => {
                      e.preventDefault();
                      if (item.col) window.dispatchEvent(new CustomEvent('set-collection-filter', { detail: item.col }));
                      setPage('collection');
                    }}
                  >
                    {item.label}
                  </a>
                </li>
              ))}
            </ul>
          </div>

          {/* Atelier */}
          <div>
            <h5>Atelier</h5>
            <ul>
              {navLinks.atelier.map((item) => (
                <li key={item.label}>
                  <a
                    href={item.path}
                    onClick={(e) => handleNav(e, item.key)}
                  >
                    {item.label}
                  </a>
                </li>
              ))}
            </ul>
          </div>

          {/* Connect */}
          <div>
            <h5>Connect</h5>
            <ul>
              {brand.instagram && (
                <li>
                  <a
                    href={brand.instagram}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    Instagram
                  </a>
                </li>
              )}

              {brand.tiktok && (
                <li>
                  <a
                    href={brand.tiktok}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    TikTok
                  </a>
                </li>
              )}

              <li>
                <a href={`mailto:${brand.contactEmail || 'info@aurellebride.com'}`}>
                  {brand.contactEmail || 'info@aurellebride.com'}
                </a>
              </li>

              <li>
                <a
                  href={`https://wa.me/${(brand.whatsapp || '').replace(/\D/g, '')}`}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  WhatsApp Us
                </a>
              </li>
            </ul>
          </div>
        </div>

        <div className="footrow">
          <span>
            © {new Date().getFullYear()} {brand.brandName}. All rights reserved.
          </span>

          <span
            style={{
              fontFamily: 'var(--mono)',
              fontSize: 10
            }}
          >
            KARACHI · WORLDWIDE SHIPPING
          </span>
        </div>
      </div>
    </footer>
  );
}

// ──────────────────────────────────────────────────────────────
//  CONTACT PAGE
// ──────────────────────────────────────────────────────────────
function ContactPage() {
  const [form, setForm] = useState({ name: '', email: '', phone: '', phone_whatsapp: true, subject: '', detail: '', call_back: false, call_time: '' });
  const [sent, setSent] = useState(false);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = async () => {
    if (!form.name || !form.email || !form.phone) return;
    try {
      const recaptchaToken = await getRecaptchaToken('contact');
      await fetch('/api/inquiries.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...form, recaptcha_token: recaptchaToken }) });
      setSent(true);
    } catch { alert('Please try again or WhatsApp us directly.'); }
  };

  return (
    <section className="section">
      <div className="container" style={{ maxWidth: 680 }}>
        <div style={{ textAlign: 'center', marginBottom: 52 }}>
          <span className="eyebrow" style={{ display: 'block', marginBottom: 14 }}><span className="dot" />Get in Touch</span>
          <h1 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(34px,4vw,52px)', marginBottom: 14 }}>We'd love to hear from you</h1>
          <p style={{ color: 'var(--ink-2)' }}>Inquiries, collaborations, press — we're here.</p>
        </div>
        {sent ? (
          <div className="card" style={{ padding: 48, textAlign: 'center' }}>
            <div style={{ fontSize: 48, marginBottom: 14 }}>✉️</div>
            <h3 style={{ fontFamily: 'var(--serif)', fontSize: 24, marginBottom: 10 }}>Message received</h3>
            <p style={{ color: 'var(--ink-2)' }}>We'll get back to you within 24 hours. For urgent matters, WhatsApp us.</p>
          </div>
        ) : (
          <div className="card" style={{ padding: 36, display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div className="grid-2">
              <Field label="Name" required><input className="input" value={form.name} onChange={e => set('name', e.target.value)} /></Field>
              <Field label="Email" required><input className="input" type="email" value={form.email} onChange={e => set('email', e.target.value)} /></Field>
            </div>
            <div className="grid-2">
              <PhoneInput label="Phone Number" required
                onChange={(full) => set('phone', full)} />
              <Field label="Available on WhatsApp?">
                <label style={{ display:'flex', alignItems:'center', gap:10, cursor:'pointer', height:42, fontSize:14 }}>
                  <input type="checkbox" checked={form.phone_whatsapp}
                    onChange={e => set('phone_whatsapp', e.target.checked)}
                    style={{ width:18, height:18, accentColor:'var(--gold)' }} />
                  <span>Yes, this number is on WhatsApp</span>
                </label>
              </Field>
            </div>
            <Field label="Subject"><input className="input" placeholder="e.g. Bridal inquiry, Press, Wholesale" value={form.subject} onChange={e => set('subject', e.target.value)} /></Field>
            <Field label="Message"><textarea className="textarea" placeholder="Tell us how we can help…" value={form.detail} onChange={e => set('detail', e.target.value)} /></Field>
            <label style={{ display: 'flex', gap: 10, alignItems: 'center', cursor: 'pointer', fontSize: 14 }}>
              <input type="checkbox" checked={form.call_back} onChange={e => set('call_back', e.target.checked)} style={{ width: 18, height: 18, accentColor: 'var(--gold)' }} />
              I'd like a call back
            </label>
            {form.call_back && (
              <Field label="Best time to call">
                <input className="input" placeholder="e.g. Weekdays 3–7 PM PKT" value={form.call_time} onChange={e => set('call_time', e.target.value)} />
              </Field>
            )}
            <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end', marginTop: 8 }}>
              <button className="btn btn-primary btn-lg" onClick={handleSubmit}>Send Message</button>
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

// ──────────────────────────────────────────────────────────────
//  HOMEPAGE
// ──────────────────────────────────────────────────────────────
function HomePage({ setPage, onSelectProduct, onOrder }) {
  return (
    <>
      <HeroSection setPage={setPage} />
      <MarqueeStrip />
      <CollectionSection onSelectProduct={onSelectProduct} limit={4} />
      <ReviewsSection />
      <JournalSection limit={3} />
      <div style={{ padding: '80px 0', textAlign: 'center', background: 'var(--surface)', borderBlock: '1px solid var(--line)' }}>
        <div className="container" style={{ maxWidth: 600 }}>
          <span className="eyebrow" style={{ display: 'block', marginBottom: 14 }}><span className="dot" />Design yours</span>
          <h2 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(32px,4vw,52px)', marginBottom: 16 }}>Nothing like yours <em style={{ fontStyle: 'italic', color: 'var(--gold)' }}>exists yet</em></h2>
          <p style={{ color: 'var(--ink-2)', marginBottom: 32 }}>Tell us your vision — we'll sketch it, source the fabrics, and deliver a one-of-one garment to your door, anywhere in the world.</p>
          <button className="btn btn-primary btn-lg" onClick={() => setPage('custom')}>Start Custom Order →</button>
        </div>
      </div>
    </>
  );
}
function trackPageView() {
  if (typeof gtag === 'function') {
    gtag('event', 'page_view', {
      page_title: document.title,
      page_location: window.location.href,
      page_path: window.location.pathname
    });
  }
}
// ──────────────────────────────────────────────────────────────
//  ROOT APP
// ──────────────────────────────────────────────────────────────
function App() {
  const [page, setPageState] = useState('home');
  const [theme, setTheme] = useState('dark');
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [orderProduct, setOrderProduct] = useState(null);

  // Route mapping
  const routeToPage = (pathname) => {
    const clean = pathname.replace(/\/+$/, '') || '/';

    if (clean === '/') return 'home';
    if (clean === '/collection') return 'collection';
    if (clean === '/custom') return 'custom';
    if (clean === '/journal') return 'journal';
    if (clean === '/contact') return 'contact';

    // admin
    if (clean.startsWith('/kr/pk/admin/moon')) {
      return clean.replace(/^\//, '');
    }

    return 'home';
  };

  const pageToRoute = (pageName) => {
    if (pageName === 'home') return '/';
    if (pageName === 'collection') return '/collection';
    if (pageName === 'custom') return '/custom';
    if (pageName === 'journal') return '/journal';
    if (pageName === 'contact') return '/contact';

    if (pageName.startsWith('kr/pk/admin/moon')) {
      return '/' + pageName;
    }

    return '/';
  };

const setPage = (nextPage) => {
  const target = pageToRoute(nextPage);

  if (window.location.pathname !== target) {
    window.history.pushState({}, '', target);
  }

  setPageState(nextPage);

  trackPageView();

  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  // Initial route detection
  useEffect(() => {
    setPageState(routeToPage(window.location.pathname));
    trackPageView();
  }, []);

  // Browser back/forward support
  useEffect(() => {
const handler = () => {
  setPageState(routeToPage(window.location.pathname));

  trackPageView();

  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

    window.addEventListener('popstate', handler);

    return () => {
      window.removeEventListener('popstate', handler);
    };
  }, []);

  const handleSelectProduct = (p) => setSelectedProduct(p);

  const handleOrder = (p) => {
    setOrderProduct(p);
    setPage('custom');
  };

  // Admin route
  if (page.startsWith('kr/pk/admin/moon')) {
    const subroute = page
      .replace('kr/pk/admin/moon', '')
      .replace(/^\//, '');

    return <AdminRouter subroute={subroute} />;
  }

  return (
    <>
      <SiteNav
        page={page}
        setPage={setPage}
        theme={theme}
        setTheme={setTheme}
      />

      {page === 'home' && (
        <HomePage
          setPage={setPage}
          onSelectProduct={handleSelectProduct}
          onOrder={handleOrder}
        />
      )}

      {page === 'collection' && (
        <CollectionSection
          onSelectProduct={handleSelectProduct}
        />
      )}

      {page === 'custom' && (
        <CustomOrderSection
          preProduct={orderProduct}
          onSuccess={() => setOrderProduct(null)}
        />
      )}

      {page === 'journal' && <JournalSection />}
      {page === 'contact' && <ContactPage />}

      <SiteFooter setPage={setPage} />
      <WhatsAppFAB />

      {selectedProduct && (
        <ProductModal
          product={selectedProduct}
          onClose={() => setSelectedProduct(null)}
          onOrder={handleOrder}
        />
      )}
    </>
  );
}

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