// Rental page with filters, fleet grid, and detail drawer with floorplan

const { useState: useStateR, useMemo: useMemoR } = React;

function FilterBar({ filters, setFilters, count }) {
  const groups = {
    type: { label: 'Type', options: ['All', 'Solo', 'Couples', 'Family', 'Group'] },
    sleeps: { label: 'Sleeps', options: ['Any', '2', '4', '5+'] },
    transmission: { label: 'Transmission', options: ['Any', 'Auto', 'Manual'] },
    license: { label: 'License', options: ['Any', 'B/D', 'D', 'E'] },
  };
  return (
    <div className="rental-toolbar">
      <div className="wrap">
        <div className="rental-toolbar-inner">
          {Object.entries(groups).map(([key, g]) => (
            <React.Fragment key={key}>
              <div style={{display:'flex', gap:6, alignItems:'center'}}>
                <span style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'0.14em', color:'var(--ink-soft)', marginRight:6, textTransform:'uppercase'}}>
                  {g.label}
                </span>
                {g.options.map(opt => (
                  <button key={opt}
                    className={`filter-pill ${filters[key] === opt ? 'active' : ''}`}
                    onClick={() => setFilters(f => ({...f, [key]: opt}))}>
                    {opt}
                  </button>
                ))}
              </div>
              <div className="filter-sep"/>
            </React.Fragment>
          ))}
          <span className="toolbar-results">{count} VANS · 04 AVAILABLE</span>
        </div>
      </div>
    </div>
  );
}

function RentalCard({ vehicle, onOpen }) {
  return (
    <div className="rental-card" onClick={() => onOpen(vehicle)}>
      <div className="rental-card-img" style={{backgroundImage:`url(${vehicle.image})`}}>
        <span className="rental-card-tag">{vehicle.tag}</span>
        <span className={`rental-card-avail ${vehicle.available ? '' : 'unavailable'}`}>
          {vehicle.available ? 'Available' : 'Booked'}
        </span>
      </div>
      <div className="rental-card-body">
        <div className="rental-card-name">{vehicle.name}</div>
        <div className="rental-card-sub">{vehicle.sub}</div>
        <div className="rental-card-specs">
          <span><Icon.Bed/> Sleeps {vehicle.sleeps}</span>
          <span><Icon.Seat/> {vehicle.seats} seats</span>
          <span><Icon.Ruler/> {vehicle.length}</span>
          <span><Icon.Gear/> {vehicle.transmission}</span>
        </div>
        <div className="rental-card-foot">
          <div className="rental-card-price">RM {vehicle.price}<small>/ night</small></div>
          <span className="rental-card-cta">View <Icon.ArrowSm/></span>
        </div>
      </div>
    </div>
  );
}

function Floorplan() {
  const [active, setActive] = useStateR(FLOORPLAN_HOTSPOTS[0].id);
  const cur = FLOORPLAN_HOTSPOTS.find(h => h.id === active);

  return (
    <div className="floorplan">
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16}}>
        <h4 style={{fontFamily:'var(--serif)', fontSize:20, fontWeight:400, margin:0}}>Interior floorplan</h4>
        <span style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'0.14em', color:'var(--ink-soft)'}}>TAP HOTSPOTS</span>
      </div>
      <div className="floorplan-svg-wrap">
        <svg viewBox="0 0 560 200" style={{width:'100%', height:'auto', display:'block'}}>
          {/* Body outline */}
          <rect x="20" y="30" width="520" height="140" rx="22" fill="none" stroke="#2d3a2e" strokeWidth="1.5"/>
          {/* Cab area */}
          <path d="M 540 30 Q 555 30 555 50 L 555 150 Q 555 170 540 170" fill="none" stroke="#2d3a2e" strokeWidth="1.5"/>
          <line x1="510" y1="30" x2="510" y2="170" stroke="#2d3a2e" strokeWidth="0.5" strokeDasharray="3 3"/>
          {/* Driver/passenger seats */}
          <rect x="518" y="50" width="22" height="40" rx="4" fill="#c8a781" opacity="0.5"/>
          <rect x="518" y="110" width="22" height="40" rx="4" fill="#c8a781" opacity="0.5"/>
          {/* Bed (over cab) */}
          <rect x="40" y="40" width="120" height="50" rx="6" fill="#c8a781" opacity="0.35"/>
          <text x="100" y="70" textAnchor="middle" fontFamily="Geist Mono" fontSize="10" fill="#2d3a2e" letterSpacing="1">BED</text>
          {/* Kitchen */}
          <rect x="180" y="40" width="120" height="40" rx="4" fill="#2d3a2e" opacity="0.15"/>
          <circle cx="210" cy="60" r="8" fill="none" stroke="#2d3a2e" strokeWidth="1"/>
          <circle cx="230" cy="60" r="8" fill="none" stroke="#2d3a2e" strokeWidth="1"/>
          <rect x="250" y="50" width="40" height="20" rx="2" fill="none" stroke="#2d3a2e" strokeWidth="1"/>
          {/* Dinette */}
          <rect x="180" y="100" width="60" height="60" rx="4" fill="#c8a781" opacity="0.3"/>
          <rect x="244" y="100" width="56" height="60" rx="4" fill="#c8a781" opacity="0.3"/>
          <text x="270" y="135" textAnchor="middle" fontFamily="Geist Mono" fontSize="10" fill="#2d3a2e" letterSpacing="1">DINETTE</text>
          {/* Wet bath */}
          <rect x="320" y="40" width="100" height="120" rx="4" fill="#2d3a2e" opacity="0.1"/>
          <circle cx="370" cy="100" r="18" fill="none" stroke="#2d3a2e" strokeWidth="1" strokeDasharray="2 2"/>
          <text x="370" y="103" textAnchor="middle" fontFamily="Geist Mono" fontSize="10" fill="#2d3a2e" letterSpacing="1">WC</text>
          {/* Lounge/storage */}
          <rect x="440" y="40" width="60" height="120" rx="4" fill="#c8a781" opacity="0.25"/>

          {/* Hotspots */}
          {FLOORPLAN_HOTSPOTS.map(h => (
            <g key={h.id} className={`fp-hotspot ${active === h.id ? 'active' : ''}`}
              onClick={() => setActive(h.id)}>
              <circle cx={h.x} cy={h.y} r="14" fill={active === h.id ? '#b65232' : '#f3ece0'} stroke="#2d3a2e" strokeWidth="1.5"/>
              <text x={h.x} y={h.y + 4} textAnchor="middle" fontFamily="Geist Mono" fontSize="11" fill={active === h.id ? '#f3ece0' : '#2d3a2e'} fontWeight="600">
                {FLOORPLAN_HOTSPOTS.indexOf(h) + 1}
              </text>
            </g>
          ))}
        </svg>
      </div>
      <div className="fp-detail">
        <h5>{cur.label}</h5>
        <p>{cur.desc}</p>
      </div>
    </div>
  );
}

function RentalDrawer({ vehicle, onClose, bookingState, onBook }) {
  const [tab, setTab] = useStateR('overview');
  if (!vehicle) return null;

  const nights = bookingState?.start && bookingState?.end
    ? Math.ceil((bookingState.end - bookingState.start) / 86400000) : 0;
  const total = nights * vehicle.price;

  return (
    <>
      <div className="drawer-bg" onClick={onClose}/>
      <div className="drawer">
        <div className="drawer-close">
          <span style={{fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.14em', color:'var(--ink-soft)'}}>
            {vehicle.tag.toUpperCase()} / {vehicle.id.toUpperCase()}
          </span>
          <button onClick={onClose} aria-label="Close"><Icon.Close/></button>
        </div>
        <div className="drawer-body">
          <div className="drawer-gallery">
            {vehicle.gallery.map((src, i) => (
              <div key={i} style={{backgroundImage:`url(${src})`}}/>
            ))}
          </div>
          <span className="drawer-sub">{vehicle.sub}</span>
          <h2>{vehicle.name}</h2>

          <div className="tab-row">
            {[
              { id: 'overview', label: 'Overview' },
              { id: 'specs', label: 'Specs' },
              { id: 'floorplan', label: 'Floorplan' },
              { id: 'price', label: 'Pricing' },
            ].map(t => (
              <button key={t.id}
                className={`tab ${tab === t.id ? 'active' : ''}`}
                onClick={() => setTab(t.id)}>
                {t.label}
              </button>
            ))}
          </div>

          {tab === 'overview' && (
            <div>
              <p style={{fontSize:16, lineHeight:1.65, marginTop:0}}>{vehicle.desc}</p>
              <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:16, marginTop:24}}>
                {[
                  { icon: <Icon.Bed/>, label: 'Sleeps', val: vehicle.sleeps },
                  { icon: <Icon.Seat/>, label: 'Seats', val: vehicle.seats },
                  { icon: <Icon.Ruler/>, label: 'Length', val: vehicle.length },
                  { icon: <Icon.License/>, label: 'License', val: vehicle.license },
                ].map((s, i) => (
                  <div key={i} style={{padding:'18px 14px', background:'var(--cream-2)', borderRadius:6, textAlign:'center'}}>
                    <div style={{color:'var(--sienna)', marginBottom:8, display:'flex', justifyContent:'center'}}>{s.icon}</div>
                    <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'0.12em', color:'var(--ink-soft)', marginBottom:4}}>
                      {s.label.toUpperCase()}
                    </div>
                    <div style={{fontFamily:'var(--serif)', fontSize:20}}>{s.val}</div>
                  </div>
                ))}
              </div>
              <h4 style={{fontFamily:'var(--serif)', fontSize:24, fontWeight:400, margin:'32px 0 12px'}}>What's included</h4>
              <ul style={{paddingLeft:0, listStyle:'none', display:'grid', gridTemplateColumns:'1fr 1fr', gap:'10px 24px'}}>
                {['Unlimited Peninsula miles', 'Comprehensive insurance', 'RFID + first tank fuel', 'Bedding & towel set', 'Camp chairs & table', '24/7 roadside support'].map(item => (
                  <li key={item} style={{display:'flex', gap:10, alignItems:'center', fontSize:14}}>
                    <span style={{color:'var(--sienna)'}}><Icon.Check/></span> {item}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {tab === 'specs' && (
            <div className="spec-grid">
              {Object.entries(vehicle.specs).map(([k, v]) => (
                <div key={k} className="spec-row">
                  <div className="spec-label">{k}</div>
                  <div className="spec-value">{v}</div>
                </div>
              ))}
            </div>
          )}

          {tab === 'floorplan' && <Floorplan/>}

          {tab === 'price' && (
            <div>
              <div style={{padding:'24px', background:'var(--cream-2)', borderRadius:6}}>
                <div style={{display:'flex', justifyContent:'space-between', padding:'10px 0', borderBottom:'1px solid var(--line)'}}>
                  <span>Daily rate</span>
                  <span>RM {vehicle.price}</span>
                </div>
                <div style={{display:'flex', justifyContent:'space-between', padding:'10px 0', borderBottom:'1px solid var(--line)'}}>
                  <span>Nights</span>
                  <span>× {nights || '—'}</span>
                </div>
                <div style={{display:'flex', justifyContent:'space-between', padding:'10px 0', borderBottom:'1px solid var(--line)'}}>
                  <span>Comprehensive insurance</span>
                  <span style={{color:'var(--sienna)'}}>Included</span>
                </div>
                <div style={{display:'flex', justifyContent:'space-between', padding:'10px 0', borderBottom:'1px solid var(--line)'}}>
                  <span>Peninsular miles</span>
                  <span style={{color:'var(--sienna)'}}>Unlimited</span>
                </div>
                <div style={{display:'flex', justifyContent:'space-between', padding:'16px 0 6px', fontFamily:'var(--serif)', fontSize:24}}>
                  <span>Subtotal</span>
                  <span>RM {total ? total.toLocaleString() : '—'}</span>
                </div>
              </div>
              <p style={{fontSize:13, color:'var(--ink-soft)', marginTop:16}}>
                Free cancellation up to 14 days before pickup. No deposit on weeknight pickups. Final price confirmed by our team within 1 hour.
              </p>
            </div>
          )}

          <div className="book-summary">
            <div className="book-summary-left">
              <small>
                {bookingState?.start && bookingState?.end
                  ? `${formatDate(bookingState.start)} → ${formatDate(bookingState.end)} · ${nights} NIGHTS`
                  : 'NO DATES SELECTED'}
              </small>
              <strong>{total ? `RM ${total.toLocaleString()}` : `RM ${vehicle.price} / night`}</strong>
            </div>
            <button className="btn btn-accent" onClick={() => onBook(vehicle)} disabled={!vehicle.available}>
              {vehicle.available ? 'Reserve now' : 'Join waitlist'} <Icon.Arrow/>
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

function RentalPage({ bookingState, setBookingState, onToast }) {
  const [filters, setFilters] = useStateR({ type: 'All', sleeps: 'Any', transmission: 'Any', license: 'Any' });
  const [openVehicle, setOpenVehicle] = useStateR(null);

  const filtered = useMemoR(() => {
    return FLEET.filter(v => {
      if (filters.type !== 'All' && v.tag !== filters.type) return false;
      if (filters.sleeps !== 'Any') {
        if (filters.sleeps === '5+' && v.sleeps < 5) return false;
        else if (filters.sleeps !== '5+' && String(v.sleeps) !== filters.sleeps) return false;
      }
      if (filters.transmission !== 'Any' && v.transmission !== filters.transmission) return false;
      if (filters.license !== 'Any' && v.license !== filters.license) return false;
      return true;
    });
  }, [filters]);

  const onBook = (v) => {
    setOpenVehicle(null);
    onToast(`${v.name} reserved — our team will confirm within 1 hour.`);
  };

  return (
    <div className="page">
      <section className="rental-hero">
        <div className="wrap">
          <span className="eyebrow" style={{color:'var(--tan)'}}>Rental fleet · Klang HQ</span>
          <h1>Six builds. Pick the one <em>that's already going</em> where you're going.</h1>
          <p>Every motorhome below is hand-built and maintained in our Klang workshop. Photographed exactly as you'll find it. Pick a date, lock the keys.</p>
        </div>
      </section>

      <div className="wrap" style={{marginTop:-40, position:'relative', zIndex:10}}>
        <BookingStrip initial={bookingState} onSubmit={setBookingState}/>
      </div>

      <FilterBar filters={filters} setFilters={setFilters} count={String(filtered.length).padStart(2,'0')}/>

      <div className="wrap">
        <div className="rental-grid">
          {filtered.map(v => <RentalCard key={v.id} vehicle={v} onOpen={setOpenVehicle}/>)}
        </div>
        {filtered.length === 0 && (
          <div style={{textAlign:'center', padding:'120px 0'}}>
            <h3 style={{fontFamily:'var(--serif)', fontSize:32, fontWeight:400}}>Nothing matches that combination — yet.</h3>
            <p style={{color:'var(--ink-soft)'}}>Loosen a filter, or call our team. We sometimes hold builds back for repeat customers.</p>
          </div>
        )}
      </div>

      {openVehicle && (
        <RentalDrawer
          vehicle={openVehicle}
          onClose={() => setOpenVehicle(null)}
          bookingState={bookingState}
          onBook={onBook}
        />
      )}
    </div>
  );
}

window.RentalPage = RentalPage;
