// Shared: Nav, Footer, WhatsApp FAB, DatePicker, BookingStrip, Toast

const { useState, useEffect, useRef, useMemo, useCallback } = React;

function Nav({ page, setPage }) {
  const links = [
    { id: 'home', label: 'Home' },
    { id: 'rental', label: 'Rental' },
    { id: 'modification', label: 'Modification' },
    { id: 'motorhomes', label: 'Motorhomes' },
    { id: 'about', label: 'About' },
    { id: 'contact', label: 'Contact' },
  ];
  return (
    <nav className="nav">
      <div className="wrap nav-inner">
        <a className="brand" onClick={() => setPage('home')} style={{cursor:'pointer'}}>
          <img src="images/vr-logo.png" alt="VR Motorhome & Caravan" className="brand-logo"/>
        </a>
        <div className="nav-links">
          {links.map(l => (
            <a key={l.id}
              className={`nav-link ${page === l.id ? 'active' : ''}`}
              onClick={() => setPage(l.id)}
              style={{cursor:'pointer'}}>
              {l.label}
            </a>
          ))}
        </div>
        <a className="nav-cta" onClick={() => setPage('rental')} style={{cursor:'pointer'}}>
          Book a rental
        </a>
      </div>
    </nav>
  );
}

function Footer({ setPage }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <img src="images/vr-logo.png" alt="VR Motorhome & Caravan" className="footer-logo"/>
            <p className="footer-tag">Selangor's home for motorhome rentals, modifications and sales since 2016. Built in Malaysia, ready for any road.</p>
          </div>
          <div className="footer-col">
            <h4>Visit</h4>
            <ul>
              <li><a>Klang HQ</a></li>
              <li><a>Hours · Mon–Sat 9–6</a></li>
              <li><a>+6019 900 0762</a></li>
              <li><a>vrmotorhome@gmail.com</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Explore</h4>
            <ul>
              <li><a onClick={() => setPage('home')} style={{cursor:'pointer'}}>Home</a></li>
              <li><a onClick={() => setPage('rental')} style={{cursor:'pointer'}}>Rental fleet</a></li>
              <li><a>Modifications</a></li>
              <li><a>Pre-order</a></li>
              <li><a>Accessories</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Follow</h4>
            <ul>
              <li><a>Instagram</a></li>
              <li><a>TikTok</a></li>
              <li><a>YouTube</a></li>
              <li><a>Xiaohongshu</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2016–2026 VR Motorhome & Caravan Sdn Bhd · 201601001555 (1172481-W)</span>
          <span>Selangor · Malaysia</span>
        </div>
      </div>
    </footer>
  );
}

function WhatsAppFab() {
  const [show, setShow] = useState(true);
  useEffect(() => {
    const t = setTimeout(() => setShow(false), 8000);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className="wa-fab">
      {show && (
        <div className="wa-bubble">
          <strong>Need help?</strong>
          Plan your trip with our team on WhatsApp — replies in &lt; 5 min.
        </div>
      )}
      <button className="wa-btn" aria-label="WhatsApp" onClick={() => setShow(s => !s)}>
        <Icon.Wa/>
      </button>
    </div>
  );
}

function Toast({ message, onDone }) {
  useEffect(() => {
    const t = setTimeout(onDone, 2800);
    return () => clearTimeout(t);
  }, [message, onDone]);
  return (
    <div className="toast">
      <span className="check"><Icon.Check size={12}/></span>
      {message}
    </div>
  );
}

// ---------- CountUp — animates number when scrolled into view ----------
function CountUp({ to, from = 0, duration = 1400, suffix = '', prefix = '', decimals = 0 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(from);
  useEffect(() => {
    if (!ref.current) return;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (!e.isIntersecting) return;
        obs.disconnect();
        if (reduce) { setVal(to); return; }
        const start = performance.now();
        const tick = () => {
          const elapsed = performance.now() - start;
          const t = Math.min(elapsed / duration, 1);
          const eased = 1 - Math.pow(1 - t, 3);
          setVal(from + (to - from) * eased);
          if (t < 1) requestAnimationFrame(tick);
          else setVal(to);
        };
        requestAnimationFrame(tick);
      });
    }, { threshold: 0.4 });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [to, from, duration]);
  const display = decimals > 0 ? val.toFixed(decimals) : Math.round(val);
  return <span ref={ref}>{prefix}{display}{suffix}</span>;
}

// ---------- DatePicker ----------
const MONTH_NAMES = ['January','February','March','April','May','June','July','August','September','October','November','December'];
const DOW = ['S','M','T','W','T','F','S'];

function formatDate(d) {
  if (!d) return null;
  return `${d.getDate()} ${MONTH_NAMES[d.getMonth()].slice(0,3)}`;
}

function DatePicker({ start, end, onChange, onClose }) {
  const [view, setView] = useState(() => start || new Date(2026, 5, 1));
  const ref = useRef(null);

  useEffect(() => {
    function handle(e) {
      if (ref.current && !ref.current.contains(e.target)) onClose && onClose();
    }
    document.addEventListener('mousedown', handle);
    return () => document.removeEventListener('mousedown', handle);
  }, [onClose]);

  function navMonth(delta) {
    setView(v => new Date(v.getFullYear(), v.getMonth() + delta, 1));
  }

  function pickDay(day) {
    const picked = new Date(view.getFullYear(), view.getMonth(), day);
    if (!start || (start && end)) {
      onChange({ start: picked, end: null });
    } else if (picked < start) {
      onChange({ start: picked, end: null });
    } else {
      onChange({ start, end: picked });
    }
  }

  const year = view.getFullYear();
  const month = view.getMonth();
  const firstDow = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const today = new Date(); today.setHours(0,0,0,0);

  const cells = [];
  for (let i = 0; i < firstDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);

  function isSameDay(a, b) {
    return a && b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
  }

  return (
    <div className="popover" ref={ref} onClick={e => e.stopPropagation()}>
      <div className="cal-head">
        <div className="cal-nav">
          <button onClick={() => navMonth(-1)} aria-label="Previous month"><Icon.Chev dir="left"/></button>
        </div>
        <h4>{MONTH_NAMES[month]} {year}</h4>
        <div className="cal-nav">
          <button onClick={() => navMonth(1)} aria-label="Next month"><Icon.Chev dir="right"/></button>
        </div>
      </div>
      <div className="cal-grid">
        {DOW.map((d, i) => <div key={i} className="cal-dow">{d}</div>)}
        {cells.map((day, i) => {
          if (!day) return <div key={i}/>;
          const date = new Date(year, month, day);
          const disabled = date < today;
          const isStart = isSameDay(date, start);
          const isEnd = isSameDay(date, end);
          const inRange = start && end && date > start && date < end;
          const classes = ['cal-day'];
          if (disabled) classes.push('disabled');
          if (isStart) classes.push('start');
          if (isEnd) classes.push('end');
          if (inRange) classes.push('in-range');
          return (
            <div key={i} className={classes.join(' ')}
              onClick={() => !disabled && pickDay(day)}>
              {day}
            </div>
          );
        })}
      </div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:16, paddingTop:16, borderTop:'1px solid var(--line)'}}>
        <span style={{fontFamily:'var(--mono)', fontSize:11, color:'var(--ink-soft)', letterSpacing:'0.1em'}}>
          {start && end ? `${Math.ceil((end - start) / 86400000)} NIGHTS` : start ? 'PICK CHECK-OUT' : 'PICK CHECK-IN'}
        </span>
        <button className="btn btn-primary" style={{padding:'8px 18px', fontSize:12}} onClick={onClose}>Done</button>
      </div>
    </div>
  );
}

function BookingStrip({ onSubmit, initial }) {
  const [pickup, setPickup] = useState(initial?.pickup || 'Klang HQ');
  const [dates, setDates] = useState({ start: initial?.start || null, end: initial?.end || null });
  const [travellers, setTravellers] = useState(initial?.travellers || 2);
  const [showPicker, setShowPicker] = useState(false);
  const [showLoc, setShowLoc] = useState(false);
  const [showTrav, setShowTrav] = useState(false);

  return (
    <div className="boarding">
      <div className="boarding-row">
        <div className="boarding-cell"
          onClick={() => { setShowLoc(s=>!s); setShowPicker(false); setShowTrav(false); }}>
          <span className="boarding-cell-label">Location</span>
          <span className="boarding-cell-value">{pickup}</span>
          <span className="boarding-cell-meta">Selangor depot</span>
          {showLoc && (
            <div className="popover" style={{minWidth:240, padding:8, top:'calc(100% + 6px)', left:16}} onClick={e => e.stopPropagation()}>
              {['Klang HQ', 'KLIA / KLIA2', 'KL Sentral', 'Penang (delivery)'].map(loc => (
                <div key={loc} style={{padding:'12px 14px', borderRadius:4, cursor:'pointer', fontSize:14}}
                  onMouseEnter={e => e.currentTarget.style.background='rgba(13,13,10,0.05)'}
                  onMouseLeave={e => e.currentTarget.style.background='transparent'}
                  onClick={() => { setPickup(loc); setShowLoc(false); }}>
                  {loc}
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="boarding-cell"
          onClick={() => { setShowPicker(true); setShowLoc(false); setShowTrav(false); }}>
          <span className="boarding-cell-label">Pick-up</span>
          <span className={`boarding-cell-value ${!dates.start ? 'placeholder' : ''}`}>
            {dates.start ? formatDate(dates.start) : 'Select date'}
          </span>
          <span className="boarding-cell-meta">From 09:00</span>
          {showPicker && (
            <DatePicker start={dates.start} end={dates.end}
              onChange={setDates}
              onClose={() => setShowPicker(false)}/>
          )}
        </div>

        <div className="boarding-cell"
          onClick={() => { setShowPicker(true); setShowLoc(false); setShowTrav(false); }}>
          <span className="boarding-cell-label">Drop-off</span>
          <span className={`boarding-cell-value ${!dates.end ? 'placeholder' : ''}`}>
            {dates.end ? formatDate(dates.end) : 'Select date'}
          </span>
          <span className="boarding-cell-meta">By 18:00</span>
        </div>

        <div className="boarding-cell"
          onClick={() => { setShowTrav(s=>!s); setShowLoc(false); setShowPicker(false); }}>
          <span className="boarding-cell-label">Travellers</span>
          <span className="boarding-cell-value">{travellers} {travellers === 1 ? 'guest' : 'guests'}</span>
          <span className="boarding-cell-meta">1 driver included</span>
          {showTrav && (
            <div className="popover" style={{minWidth:220, padding:16, top:'calc(100% + 6px)', right:16}} onClick={e => e.stopPropagation()}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                <span style={{fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.12em', color:'var(--ink-soft)'}}>TRAVELLERS</span>
                <div style={{display:'flex', gap:8, alignItems:'center'}}>
                  <button onClick={(e) => { e.stopPropagation(); setTravellers(t => Math.max(1, t-1)); }}
                    style={{width:28, height:28, borderRadius:'50%', border:'1px solid var(--line-strong)', background:'transparent', cursor:'pointer'}}>−</button>
                  <span style={{minWidth:24, textAlign:'center', fontFamily:'var(--serif)', fontSize:18}}>{travellers}</span>
                  <button onClick={(e) => { e.stopPropagation(); setTravellers(t => Math.min(8, t+1)); }}
                    style={{width:28, height:28, borderRadius:'50%', border:'1px solid var(--line-strong)', background:'transparent', cursor:'pointer'}}>+</button>
                </div>
              </div>
            </div>
          )}
        </div>

        <button className="boarding-submit"
          onClick={() => onSubmit({ pickup, ...dates, travellers })}>
          <span>Search availability</span>
          <Icon.Arrow/>
        </button>
      </div>
    </div>
  );
}

window.Nav = Nav;
window.Footer = Footer;
window.WhatsAppFab = WhatsAppFab;
window.Toast = Toast;
window.DatePicker = DatePicker;
window.BookingStrip = BookingStrip;
window.formatDate = formatDate;
window.CountUp = CountUp;
