/* ===== Big Rig shared UI ===== */
const { useState } = React;

function Ph({ label, className, style, src, alt }) {
  if (src) {
    return <img className={'ph ph-img ' + (className || '')} src={src} alt={alt || label || ''} style={style} />;
  }
  return <div className={'ph ' + (className || '')} style={style}>{label}</div>;
}

function Logo({ small }) {
  return <span className="logo" aria-label="Big Rig"><BigRigMark className="logo-mark" /></span>;
}

/* ---- international phone field ---- */
const COUNTRIES = [
  { code: 'ZA', flag: '🇿🇦', dial: '+27', name: 'South Africa', ex: '82 123 4567' },
  { code: 'NA', flag: '🇳🇦', dial: '+264', name: 'Namibia', ex: '81 123 4567' },
  { code: 'BW', flag: '🇧🇼', dial: '+267', name: 'Botswana', ex: '71 123 456' },
  { code: 'ZW', flag: '🇿🇼', dial: '+263', name: 'Zimbabwe', ex: '71 234 5678' },
  { code: 'GB', flag: '🇬🇧', dial: '+44', name: 'United Kingdom', ex: '7400 123456' },
  { code: 'US', flag: '🇺🇸', dial: '+1', name: 'United States', ex: '201 555 0123' },
  { code: 'DE', flag: '🇩🇪', dial: '+49', name: 'Germany', ex: '1512 3456789' },
  { code: 'FR', flag: '🇫🇷', dial: '+33', name: 'France', ex: '6 12 34 56 78' },
  { code: 'NL', flag: '🇳🇱', dial: '+31', name: 'Netherlands', ex: '6 12345678' },
  { code: 'ES', flag: '🇪🇸', dial: '+34', name: 'Spain', ex: '612 34 56 78' },
  { code: 'IT', flag: '🇮🇹', dial: '+39', name: 'Italy', ex: '312 345 6789' },
  { code: 'CH', flag: '🇨🇭', dial: '+41', name: 'Switzerland', ex: '78 123 45 67' },
  { code: 'AT', flag: '🇦🇹', dial: '+43', name: 'Austria', ex: '664 123456' },
  { code: 'AU', flag: '🇦🇺', dial: '+61', name: 'Australia', ex: '412 345 678' },
  { code: 'NZ', flag: '🇳🇿', dial: '+64', name: 'New Zealand', ex: '21 123 4567' },
  { code: 'CA', flag: '🇨🇦', dial: '+1', name: 'Canada', ex: '506 234 5678' },
  { code: 'IE', flag: '🇮🇪', dial: '+353', name: 'Ireland', ex: '85 123 4567' },
  { code: 'AE', flag: '🇦🇪', dial: '+971', name: 'UAE', ex: '50 123 4567' },
  { code: 'JP', flag: '🇯🇵', dial: '+81', name: 'Japan', ex: '90 1234 5678' },
];
const DEFAULT_COUNTRY = COUNTRIES[0];

function PhoneField({ country, onCountry, value, onChange, bad }) {
  return (
    <div className={'ffield phone-ff' + (bad ? ' bad' : '')} style={{ flex: 1 }}>
      <div className="lab">Phone</div>
      <div className="phone-row">
        <select className="dial-sel" value={country.code} onChange={e => onCountry(COUNTRIES.find(c => c.code === e.target.value) || DEFAULT_COUNTRY)} aria-label="Country code">
          {COUNTRIES.map(c => <option key={c.code} value={c.code}>{c.flag} {c.dial}  {c.name}</option>)}
        </select>
        <span className="dial-show">{country.flag} {country.dial}</span>
        <input value={value} onChange={e => onChange(e.target.value)} placeholder={country.ex} inputMode="tel" />
      </div>
    </div>
  );
}

function Nav({ route, go, cartCount }) {
  const [open, setOpen] = useState(false);
  const items = [['home', 'RENT'], ['shop', 'SHOP'], ['about', 'ABOUT']];
  const navTo = (r) => { setOpen(false); go(r); };
  return (
    <div className={open ? 'menu-open' : ''}>
      <div className="nav">
        <button onClick={() => navTo('home')} style={{ display: 'flex' }}><Logo /></button>
        <div className="contact-links">
          {/* TODO: wire WhatsApp — set href to https://wa.me/<full-number> */}
          <a className="contact-btn wa" href="#" target="_blank" rel="noopener" aria-label="Message us on WhatsApp">
            <svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor" aria-hidden="true"><path d="M12.04 2.2c-5.46 0-9.9 4.43-9.9 9.9 0 1.74.46 3.44 1.32 4.94L2.06 21.8l4.9-1.28a9.86 9.86 0 0 0 4.72 1.2h.01c5.46 0 9.9-4.43 9.9-9.9 0-2.64-1.03-5.13-2.9-7A9.82 9.82 0 0 0 12.04 2.2Zm0 1.8c2.16 0 4.19.84 5.72 2.37a8.04 8.04 0 0 1 2.37 5.72c0 4.47-3.64 8.1-8.1 8.1-1.49 0-2.95-.4-4.22-1.16l-.3-.18-2.91.76.78-2.84-.2-.31a8.05 8.05 0 0 1-1.24-4.31c0-4.47 3.63-8.1 8.1-8.1Zm-2.5 4.34c-.16 0-.42.06-.64.3-.22.24-.84.82-.84 2s.86 2.32.98 2.48c.12.16 1.7 2.6 4.12 3.64.58.25 1.02.4 1.37.51.58.18 1.1.16 1.51.1.46-.07 1.42-.58 1.62-1.14.2-.56.2-1.04.14-1.14-.06-.1-.22-.16-.46-.28-.24-.12-1.42-.7-1.64-.78-.22-.08-.38-.12-.54.12-.16.24-.62.78-.76.94-.14.16-.28.18-.52.06-.24-.12-1.01-.37-1.93-1.19-.71-.64-1.19-1.42-1.33-1.66-.14-.24-.01-.37.11-.49.11-.11.24-.28.36-.42.12-.14.16-.24.24-.4.08-.16.04-.3-.02-.42-.06-.12-.54-1.3-.74-1.78-.2-.47-.4-.4-.54-.41-.14-.01-.3-.01-.46-.01Z"/></svg>
            <span className="lbl">WHATSAPP</span>
          </a>
          {/* TODO: wire email — set href to mailto:<your-address> */}
          <a className="contact-btn em" href="#" aria-label="Email us">
            <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="2.5" y="4.5" width="19" height="15" rx="2"/><path d="m3 6 9 6.5L21 6"/></svg>
            <span className="lbl">EMAIL</span>
          </a>
          {/* TODO: wire Instagram — set href to https://instagram.com/<handle> */}
          <a className="contact-btn ig" href="#" target="_blank" rel="noopener" aria-label="Follow us on Instagram">
            <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="2.5" y="2.5" width="19" height="19" rx="5"/><circle cx="12" cy="12" r="4.2"/><circle cx="17.4" cy="6.6" r="1.1" fill="currentColor" stroke="none"/></svg>
            <span className="lbl">INSTAGRAM</span>
          </a>
        </div>
        <div className="nav-links">
          {items.map(([r, l]) => (
            <button key={r} className={route === r || (r === 'home' && route.indexOf('book') === 0) ? 'on' : ''} onClick={() => navTo(r)}>{l}</button>
          ))}
        </div>
        <span className="grow"></span>
        <button className="cartbtn" onClick={() => navTo('cart')}>
          <span className="lbl">CART</span>
          {cartCount > 0 ? <span className="bdg">{cartCount}</span> : <span>🛒</span>}
        </button>
        <button className="hamb" onClick={() => setOpen(!open)}>{open ? '✕' : '≡'}</button>
      </div>
      <div className="mobile-menu">
        {items.map(([r, l]) => <button key={r} onClick={() => navTo(r)}>{l}</button>)}
        <button onClick={() => navTo('cart')}>CART ({cartCount})</button>
      </div>
    </div>
  );
}

function Footer({ go }) {
  return (
    <div className="foot">
      <Logo small />
      <div className="cols">
        <div><b>RENT</b><button className="linkish" style={{ textDecoration: 'none', textAlign: 'left' }} onClick={() => go('book-dates')}>Book pads</button><button className="linkish" style={{ textDecoration: 'none', textAlign: 'left' }} onClick={() => go('shop')}>Availability</button></div>
        <div><b>SHOP</b><button className="linkish" style={{ textDecoration: 'none', textAlign: 'left' }} onClick={() => go('shop')}>All gear</button></div>
        <div><b>INFO</b><button className="linkish" style={{ textDecoration: 'none', textAlign: 'left' }} onClick={() => go('about')}>About</button></div>
      </div>
    </div>
  );
}

function Stepper({ active }) {
  const steps = [['dates', '1', 'DATES'], ['pads', '2', 'PADS'], ['confirm', '3', 'CONFIRM']];
  const order = ['dates', 'pads', 'confirm'];
  const ai = order.indexOf(active);
  return (
    <div className="stepper">
      {steps.map(([k, n, l], i) => (
        <React.Fragment key={k}>
          <div className={'step ' + (k === active ? 'on' : (i < ai ? 'done' : ''))}><span className="num">{n}</span>{l}</div>
          {i < 2 ? <span className="sep">———</span> : null}
        </React.Fragment>
      ))}
    </div>
  );
}

function Qty({ value, onChange, min, max }) {
  min = min == null ? 0 : min;
  const dec = () => onChange(Math.max(min, value - 1));
  const inc = () => { if (max == null || value < max) onChange(value + 1); };
  return (
    <div className="qty">
      <button onClick={dec} aria-label="decrease">−</button>
      <b>{value}</b>
      <button onClick={inc} disabled={max != null && value >= max} style={max != null && value >= max ? { opacity: .3, cursor: 'not-allowed' } : null}>+</button>
    </div>
  );
}

function StockBadge({ stock }) {
  if (stock <= 0) return <span className="lowstock">SOLD OUT</span>;
  if (stock <= 3) return <span className="lowstock">{stock} LEFT · LOW STOCK</span>;
  return <span className="instock">{stock} available</span>;
}

// Calendar with range selection
function Calendar({ month, setMonth, start, end, onPick }) {
  const y = month.getFullYear(), m = month.getMonth();
  const first = new Date(y, m, 1);
  const offset = (first.getDay() + 6) % 7; // Monday-first
  const daysIn = new Date(y, m + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < offset; i++) cells.push(null);
  for (let d = 1; d <= daysIn; d++) cells.push(new Date(y, m, d));
  const today = new Date(2026, 4, 29); today.setHours(0, 0, 0, 0);
  const sameDay = (a, b) => a && b && a.getTime() === b.getTime();
  const inRange = (d) => start && end && d > start && d < end;
  const canPrev = !(y === 2026 && m === 5); // June 2026 is earliest
  const canNext = !(y === 2026 && m === 8); // up to Sep 2026
  return (
    <div className="cal">
      <div className="cal-head">
        <button onClick={() => canPrev && setMonth(new Date(y, m - 1, 1))} style={canPrev ? null : { opacity: .25, cursor: 'default' }}>‹</button>
        <b>{BR.MON[m].toUpperCase()} {y}</b>
        <button onClick={() => canNext && setMonth(new Date(y, m + 1, 1))} style={canNext ? null : { opacity: .25, cursor: 'default' }}>›</button>
      </div>
      <div className="cal-grid">
        {['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((d, i) => <div key={i} className="cal-dow">{d}</div>)}
        {cells.map((d, i) => {
          if (!d) return <div key={i}></div>;
          const past = d < today;
          const cls = ['cal-day'];
          if (past) cls.push('mute');
          if (sameDay(d, start) || sameDay(d, end)) cls.push('sel');
          else if (inRange(d)) cls.push('in-range');
          return <div key={i} className={cls.join(' ')} onClick={() => !past && onPick(d)}>{d.getDate()}</div>;
        })}
      </div>
    </div>
  );
}

Object.assign(window, { Ph, Logo, Nav, Footer, Stepper, Qty, StockBadge, Calendar, PhoneField, COUNTRIES, DEFAULT_COUNTRY });
