/* global React, Icon, Badge, Tag, Avatar, Button, Field, Toggle, Tabs, Segmented, Card, Metric, Modal, Pager, AreaChart, BarChart, DonutCard, Gauge, Sparkline, ProgressBar, toast */

var { useState: useState_cr, useEffect: useEffect_cr } = React;

// ============================================================
// PAGE: CAR RENTAL — 2 tabs: Bookings + Suppliers
// ============================================================
function PageCarRental({ onNav }) {
  const [tab, setTab] = useState_cr("bookings");
  const [selected, setSelected] = useState_cr(null);
  const [view, setView] = useState_cr("list"); // "list" | "detail"

  const openBookingDetail = (b) => { setSelected(b); setView("detail"); };
  const backToList = () => { setView("list"); setSelected(null); };

  return (
    <div>
      <div style={{ background: "#fff8e1", border: "1px solid #f9c64b", borderRadius: 8, padding: "10px 14px", marginBottom: 14, fontSize: 13, color: "#7a5b00", display: "flex", gap: 8, alignItems: "center" }}>
        <Icon.Warning size={14} stroke="#7a5b00" />
        <span><strong>Demo data.</strong> Car rental backend is not yet wired — all bookings, suppliers and KPIs below are mocks. Do not act on this data.</span>
      </div>
      <div className="page-head">
        <div>
          <h1 className="page-head__title">Car Rental</h1>
          <div className="page-head__sub">Manage rental car bookings and supplier relationships</div>
        </div>
        <div className="page-head__actions">
          {tab === "bookings" && <Button kind="primary" icon={<Icon.Plus />} onClick={() => toast({ title: "Car rental backend not wired", body: "Creating a car rental booking is mock-only.", tone: "warning" })}>New booking</Button>}
          {tab === "suppliers" && <Button kind="primary" icon={<Icon.Plus />} onClick={() => toast({ title: "Car rental backend not wired", body: "Adding a supplier is mock-only.", tone: "warning" })}>Add supplier</Button>}
        </div>
      </div>

      <Tabs active={tab} onChange={setTab} tabs={[
        { id: "bookings",   label: "Bookings",   count: 2184 },
        { id: "suppliers",  label: "Suppliers",  count: 18 },
      ]} />

      {tab === "bookings" && (
        view === "list" 
          ? <CarRentalBookingList onOpenDetail={openBookingDetail} />
          : <CarRentalBookingDetail booking={selected} onBack={backToList} />
      )}
      {tab === "suppliers" && <CarRentalSuppliers />}
    </div>
  );
}

// -----------------------------------------------------------
// CAR RENTAL BOOKING LIST
// -----------------------------------------------------------
function CarRentalBookingList({ onOpenDetail }) {
  const BOOKINGS = [
    { id: "CAR-12482", ref: "CAR-12482", agency: "Optitron Travel", pickup: "Madrid Barajas T4", dropoff: "Madrid Barajas T4", pickupDate: "2024-12-18", dropoffDate: "2024-12-22", days: 4, category: "Intermediate · Sedan", vendor: "Sixt", vehicle: "VW Passat or similar", extras: "GPS, Child seat", netCost: 148, sellPrice: 222, margin: 33.3, status: "Confirmed", bookingDate: "2024-11-10", driver: "Maria Lopez", email: "maria.lopez@optitron.com" },
    { id: "CAR-12481", ref: "CAR-12481", agency: "SunTours España", pickup: "Barcelona El Prat T1", dropoff: "Barcelona El Prat T1", pickupDate: "2024-12-17", dropoffDate: "2024-12-24", days: 7, category: "Compact · Hatchback", vendor: "Europcar", vehicle: "Seat Ibiza or similar", extras: "Full insurance", netCost: 182, sellPrice: 273, margin: 33.3, status: "Confirmed", bookingDate: "2024-11-08", driver: "Hannah Briggs", email: "h.briggs@suntours.es" },
    { id: "CAR-12480", ref: "CAR-12480", agency: "Global Ventures Ltd", pickup: "Heathrow T5", dropoff: "Gatwick South", pickupDate: "2024-12-16", dropoffDate: "2024-12-20", days: 4, category: "Premium · SUV", vendor: "Hertz", vehicle: "Range Rover Evoque or similar", extras: "Premium insurance, GPS", netCost: 340, sellPrice: 510, margin: 33.3, status: "In Progress", bookingDate: "2024-11-05", driver: "John Smith", email: "j.smith@globalventures.co.uk" },
    { id: "CAR-12479", ref: "CAR-12479", agency: "Nordic Explorers", pickup: "Arlanda Airport", dropoff: "Arlanda Airport", pickupDate: "2024-12-15", dropoffDate: "2024-12-18", days: 3, category: "Standard · Sedan", vendor: "Enterprise", vehicle: "Volvo S60 or similar", extras: "None", netCost: 124, sellPrice: 186, margin: 33.3, status: "Confirmed", bookingDate: "2024-11-02", driver: "Ingrid Svensson", email: "i.svensson@nordicexplorers.se" },
    { id: "CAR-12478", ref: "CAR-12478", agency: "Optitron Travel", pickup: "Madrid Atocha Station", dropoff: "Malaga Airport", pickupDate: "2024-12-22", dropoffDate: "2024-12-28", days: 6, category: "Standard · Sedan", vendor: "Sixt", vehicle: "Seat Leon or similar", extras: "Full tank policy", netCost: 168, sellPrice: 252, margin: 33.3, status: "Pending", bookingDate: "2024-11-18", driver: "Ryan Hou", email: "r.hou@optitron.com" },
    { id: "CAR-12477", ref: "CAR-12477", agency: "SunTours España", pickup: "Valencia Airport", dropoff: "Valencia Airport", pickupDate: "2024-12-14", dropoffDate: "2024-12-21", days: 7, category: "Economy · Compact", vendor: "Budget", vehicle: "Fiat Panda or similar", extras: "Child seat x2", netCost: 142, sellPrice: 213, margin: 33.3, status: "Confirmed", bookingDate: "2024-10-28", driver: "Ana García", email: "a.garcia@suntours.es" },
    { id: "CAR-12476", ref: "CAR-12476", agency: "Global Ventures Ltd", pickup: "Charles de Gaulle T2", dropoff: "Charles de Gaulle T2", pickupDate: "2024-12-20", dropoffDate: "2024-12-27", days: 7, category: "Luxury · Sedan", vendor: "Europcar", vehicle: "BMW 5 Series or similar", extras: "Premium insurance, GPS, Additional driver", netCost: 480, sellPrice: 720, margin: 33.3, status: "Confirmed", bookingDate: "2024-11-10", driver: "Sophie Martin", email: "s.martin@globalventures.fr" },
    { id: "CAR-12475", ref: "CAR-12475", agency: "Nordic Explorers", pickup: "Copenhagen Kastrup", dropoff: "Copenhagen Kastrup", pickupDate: "2024-12-13", dropoffDate: "2024-12-16", days: 3, category: "Standard · Wagon", vendor: "Hertz", vehicle: "VW Passat Variant or similar", extras: "GPS", netCost: 148, sellPrice: 222, margin: 33.3, status: "Cancelled", bookingDate: "2024-10-22", driver: "Erik Hansen", email: "e.hansen@nordicexplorers.dk" },
  ];

  return (
    <>
      <div className="grid grid--4" style={{ marginBottom: 18 }}>
        <Metric accent label="Active bookings" value="2,184" delta="+18% YoY" deltaDir="up" />
        <Metric label="Revenue (YTD)" value="€680k" hint="All suppliers" />
        <Metric label="Avg margin" value="33.3%" hint="Net to sell" />
        <Metric label="Avg rental days" value="5.2" hint="Per booking" />
      </div>

      <div className="filter-bar">
        <input className="input" placeholder="Search ref, driver, location..." style={{ minWidth: 240 }} />
        <select className="select"><option>All agencies</option>{window.MOCK.TRAVEL_AGENCIES.slice(0, 8).map((a) => <option key={a.id}>{a.name}</option>)}</select>
        <select className="select"><option>All suppliers</option><option>Sixt</option><option>Europcar</option><option>Hertz</option><option>Enterprise</option><option>Budget</option></select>
        <select className="select"><option>All categories</option><option>Economy</option><option>Compact</option><option>Intermediate</option><option>Standard</option><option>Premium</option><option>Luxury</option></select>
        <select className="select"><option>All statuses</option><option>Confirmed</option><option>Pending</option><option>In Progress</option><option>Completed</option><option>Cancelled</option></select>
        <span className="spacer" />
        <Button kind="secondary" size="sm" icon={<Icon.Download />}>Export</Button>
      </div>

      <Card flush>
        <table className="tbl">
          <thead>
            <tr>
              <th>Ref</th><th>Pickup → Dropoff</th><th>Dates</th><th>Days</th><th>Category</th><th>Agency</th><th>Supplier</th>
              <th className="num">Net</th><th className="num">Sell</th><th className="num">Margin</th><th>Status</th><th className="col-actions"></th>
            </tr>
          </thead>
          <tbody>
            {BOOKINGS.map((b) => (
              <tr key={b.id} onClick={() => onOpenDetail(b)} style={{ cursor: "pointer" }}>
                <td className="mono bold">{b.ref}</td>
                <td>
                  <div className="bold">{b.pickup}</div>
                  <div className="tiny muted">→ {b.dropoff}</div>
                </td>
                <td className="mono">{b.pickupDate} · {b.dropoffDate}</td>
                <td className="num mono">{b.days}</td>
                <td><Tag kind="rental">{b.category}</Tag></td>
                <td className="muted">{b.agency}</td>
                <td>{b.vendor}</td>
                <td className="num mono">€{b.netCost}</td>
                <td className="num mono bold">€{b.sellPrice}</td>
                <td className="num mono" style={{ color: "var(--success)" }}>{b.margin.toFixed(1)}%</td>
                <td><TransferStatusBadge status={b.status} /></td>
                <td className="col-actions">
                  <div className="row" style={{ gap: 4, justifyContent: "flex-end" }}>
                    <Button kind="ghost" size="sm" iconOnly icon={<Icon.Edit />} title="Edit" onClick={(e) => { e.stopPropagation(); toast({ title: "Edit rental", tone: "success" }); }} />
                    <Button kind="ghost" size="sm" iconOnly icon={<Icon.Send />} title="Send voucher" onClick={(e) => { e.stopPropagation(); toast({ title: "Voucher sent", tone: "success" }); }} />
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </>
  );
}

function TransferStatusBadge({ status }) {
  const map = {
    "Confirmed":   { tone: "success", label: "Confirmed" },
    "Pending":     { tone: "warning", label: "Pending" },
    "In Progress": { tone: "info",    label: "In Progress" },
    "Completed":   { tone: "neutral", label: "Completed" },
    "Cancelled":   { tone: "danger",  label: "Cancelled" },
  };
  const s = map[status] || map.Pending;
  return <Badge tone={s.tone}>{s.label}</Badge>;
}

// -----------------------------------------------------------
// CAR RENTAL BOOKING DETAIL
// -----------------------------------------------------------
function CarRentalBookingDetail({ booking: b, onBack }) {
  const [tab, setTab] = useState_cr("overview");

  return (
    <div>
      <div className="page-head" style={{ marginTop: 0 }}>
        <div>
          <Button kind="ghost" icon={<Icon.ArrowLeft />} onClick={onBack}>Back to list</Button>
          <h1 className="page-head__title" style={{ marginTop: 8 }}>{b.ref} · {b.category}</h1>
          <div className="page-head__sub">{b.agency} · {b.pickupDate} – {b.dropoffDate} · {b.days} days</div>
        </div>
        <div className="page-head__actions">
          <TransferStatusBadge status={b.status} />
          <Button kind="secondary" icon={<Icon.Edit />}>Edit</Button>
          <Button kind="secondary" icon={<Icon.Send />}>Send voucher</Button>
          <Button kind="danger" icon={<Icon.X />} onClick={() => toast({ title: "Cancel booking", tone: "danger" })}>Cancel booking</Button>
        </div>
      </div>

      <Tabs active={tab} onChange={setTab} tabs={[
        { id: "overview", label: "Overview" },
        { id: "vehicle",  label: "Vehicle & Extras" },
        { id: "driver",   label: "Driver" },
        { id: "pricing",  label: "Pricing" },
        { id: "notes",    label: "Notes" },
      ]} />

      {tab === "overview" && (
        <div className="grid" style={{ gridTemplateColumns: "1.4fr 1fr", gap: 18 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Card title="Rental period & locations">
              <div className="grid grid--2" style={{ gap: 14 }}>
                <Field label="Pickup location"><div className="read-only">{b.pickup}</div></Field>
                <Field label="Dropoff location"><div className="read-only">{b.dropoff}</div></Field>
                <Field label="Pickup date & time"><div className="read-only mono">{b.pickupDate} 10:00</div></Field>
                <Field label="Dropoff date & time"><div className="read-only mono">{b.dropoffDate} 10:00</div></Field>
                <Field label="Rental days"><div className="read-only mono bold">{b.days} days</div></Field>
              </div>
            </Card>

            <Card title="Vehicle & Supplier">
              <div className="grid grid--2" style={{ gap: 14 }}>
                <Field label="Supplier"><div className="read-only bold">{b.vendor}</div></Field>
                <Field label="Category"><div className="read-only">{b.category}</div></Field>
                <Field label="Vehicle"><div className="read-only">{b.vehicle}</div></Field>
                <Field label="Extras"><div className="read-only">{b.extras || "None"}</div></Field>
              </div>
            </Card>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Card title="Booking info">
              <Field label="Booking reference"><div className="read-only mono bold">{b.ref}</div></Field>
              <Field label="Booked on"><div className="read-only mono">{b.bookingDate}</div></Field>
              <Field label="Agency"><div className="read-only">{b.agency}</div></Field>
              <Field label="Status"><TransferStatusBadge status={b.status} /></Field>
            </Card>

            <Card title="Pricing">
              <div className="grid grid--2" style={{ gap: 12 }}>
                <Field label="Net cost"><div className="read-only mono">€{b.netCost.toFixed(2)}</div></Field>
                <Field label="Sell price"><div className="read-only mono bold">€{b.sellPrice.toFixed(2)}</div></Field>
              </div>
              <div className="divider" />
              <div className="row" style={{ justifyContent: "space-between" }}>
                <span className="bold">Margin</span>
                <span className="bold mono" style={{ color: "var(--success)" }}>{b.margin.toFixed(1)}% (€{(b.sellPrice - b.netCost).toFixed(2)})</span>
              </div>
            </Card>

            <Card title="Main driver">
              <Field label="Name"><div className="read-only">{b.driver}</div></Field>
              <Field label="Email"><div className="read-only mono">{b.email}</div></Field>
            </Card>
          </div>
        </div>
      )}

      {tab === "vehicle" && (
        <Card title="Vehicle & Extras">
          <div className="grid grid--2" style={{ gap: 14 }}>
            <Field label="Category"><input className="input" defaultValue={b.category} /></Field>
            <Field label="Vehicle"><input className="input" defaultValue={b.vehicle} /></Field>
            <Field label="Extras / Add-ons"><textarea className="textarea" rows={3} defaultValue={b.extras} /></Field>
          </div>
          <div style={{ marginTop: 14 }}>
            <Button kind="primary">Save changes</Button>
          </div>
        </Card>
      )}

      {tab === "driver" && (
        <Card title="Main driver information">
          <div className="grid grid--2" style={{ gap: 14 }}>
            <Field label="Driver name"><input className="input" defaultValue={b.driver} /></Field>
            <Field label="Email"><input className="input" type="email" defaultValue={b.email} /></Field>
            <Field label="Phone"><input className="input" type="tel" placeholder="+34 600 000 000" /></Field>
            <Field label="Driving license number"><input className="input" placeholder="12345678X" /></Field>
          </div>
          <div style={{ marginTop: 14 }}>
            <Button kind="primary">Update driver</Button>
          </div>
        </Card>
      )}

      {tab === "pricing" && (
        <Card title="Pricing breakdown">
          <div className="grid grid--2" style={{ gap: 14 }}>
            <Field label="Net cost (from supplier)"><input className="input" type="number" defaultValue={b.netCost} step="0.01" /></Field>
            <Field label="Sell price (to agency)"><input className="input" type="number" defaultValue={b.sellPrice} step="0.01" /></Field>
          </div>
          <div className="divider" />
          <div className="row" style={{ justifyContent: "space-between", padding: "12px 0" }}>
            <span className="bold">Margin</span>
            <span className="bold mono" style={{ fontSize: 16, color: "var(--success)" }}>{b.margin.toFixed(1)}% (€{(b.sellPrice - b.netCost).toFixed(2)})</span>
          </div>
          <div style={{ marginTop: 14 }}>
            <Button kind="primary">Update pricing</Button>
          </div>
        </Card>
      )}

      {tab === "notes" && (
        <Card title="Internal notes">
          <Field label="Add note"><textarea className="textarea" rows={4} placeholder="Add internal note..." /></Field>
          <Button kind="primary" icon={<Icon.Plus />}>Add note</Button>
        </Card>
      )}
    </div>
  );
}

// -----------------------------------------------------------
// CAR RENTAL SUPPLIERS
// -----------------------------------------------------------
function CarRentalSuppliers() {
  const SUPPLIERS = window.MOCK.CAR_COMPANIES || [];

  return (
    <>
      <div className="grid grid--4" style={{ marginBottom: 18 }}>
        <Metric accent label="Active suppliers" value="18" hint="Across all markets" />
        <Metric label="YTD revenue" value="€680k" delta="+18% YoY" deltaDir="up" />
        <Metric label="Avg commission" value="22%" hint="Standard rate" />
        <Metric label="Top supplier" value="Sixt" hint="€210k revenue" />
      </div>

      <div className="filter-bar">
        <input className="input" placeholder="Search supplier..." style={{ minWidth: 240 }} />
        <select className="select"><option>All countries</option><option>Spain</option><option>UK</option><option>France</option><option>Germany</option><option>Sweden</option></select>
        <select className="select"><option>All statuses</option><option>Active</option><option>Pending</option><option>Suspended</option></select>
        <span className="spacer" />
        <Button kind="secondary" size="sm" icon={<Icon.Download />}>Export</Button>
      </div>

      <Card flush>
        <table className="tbl">
          <thead>
            <tr>
              <th>Supplier</th><th>Country</th><th>Contact</th><th className="num">Bookings YTD</th><th className="num">Revenue</th><th className="num">Commission</th><th>Status</th><th className="col-actions"></th>
            </tr>
          </thead>
          <tbody>
            {[
              { name: "Sixt Rent a Car",       country: "Germany", contact: "partners@sixt.com",     bookings: 680, revenue: 210000, commission: 22, status: "Active" },
              { name: "Europcar Mobility",     country: "France",  contact: "b2b@europcar.com",     bookings: 540, revenue: 168000, commission: 22, status: "Active" },
              { name: "Hertz",                 country: "UK",      contact: "corporate@hertz.co.uk",bookings: 420, revenue: 128000, commission: 20, status: "Active" },
              { name: "Enterprise Rent-A-Car", country: "Spain",   contact: "travel@enterprise.es", bookings: 320, revenue: 98000,  commission: 18, status: "Active" },
              { name: "Budget",                country: "Spain",   contact: "agents@budget.es",     bookings: 224, revenue: 76000,  commission: 24, status: "Active" },
            ].map((s, i) => (
              <tr key={i}>
                <td className="bold">{s.name}</td>
                <td className="muted">{s.country}</td>
                <td className="mono" style={{ fontSize: 12 }}>{s.contact}</td>
                <td className="num mono">{s.bookings}</td>
                <td className="num mono">€{s.revenue.toLocaleString()}</td>
                <td className="num mono">{s.commission}%</td>
                <td><Badge tone="success">{s.status}</Badge></td>
                <td className="col-actions">
                  <div className="row" style={{ gap: 4, justifyContent: "flex-end" }}>
                    <Button kind="ghost" size="sm" iconOnly icon={<Icon.Edit />} title="Edit" />
                    <Button kind="ghost" size="sm" iconOnly icon={<Icon.Eye />} title="View detail" />
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </>
  );
}

Object.assign(window, { PageCarRental });
