/* 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_t, useEffect: useEffect_t } = React;

// ============================================================
// PAGE: TRANSFERS — list + detail
// ============================================================
function PageTransfers({ onNav }) {
  const [view, setView] = useState_t("list"); // "list" | "detail"
  const [selected, setSelected] = useState_t(null);

  const openDetail = (t) => { setSelected(t); 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> Transfer backend is not yet wired — all transfers, vendors and KPIs below are mocks. Do not act on this data.</span>
      </div>
      {view === "list"
        ? <TransferList onOpenDetail={openDetail} />
        : <TransferDetail transfer={selected} onBack={backToList} />}
    </div>
  );
}

// -----------------------------------------------------------
// TRANSFER LIST
// -----------------------------------------------------------
function TransferList({ onOpenDetail }) {
  const [filters, setFilters] = useState_t({});
  const [page, setPage] = useState_t(1);

  const TRANSFERS = [
    { id: "TRF-12482", ref: "TRF-12482", agency: "Optitron Travel", agencyId: 1, route: "MAD Airport → Hotel Barceló", origin: "Madrid Barajas T4", dest: "Hotel Barceló Torre Madrid", date: "2024-12-18", time: "14:30", pax: 3, vendor: "Cabify Business", driver: "Carlos Martínez", vehicle: "Mercedes E-Class", plate: "2841 KLM", phone: "+34 612 345 678", netCost: 48, sellPrice: 72, margin: 33.3, status: "Confirmed", bookingDate: "2024-11-12", leadPax: "Maria Lopez", email: "maria.lopez@optitron.com", luggage: "3 large", notes: "Flight AA1042 arrives 13:45" },
    { id: "TRF-12481", ref: "TRF-12481", agency: "SunTours España", agencyId: 2, route: "BCN Airport → Costa Brava", origin: "Barcelona El Prat T1", dest: "Hotel Golden Bahia Tossa", date: "2024-12-17", time: "16:00", pax: 4, vendor: "Blacklane", driver: "Juan Pérez", vehicle: "VW Caravelle", plate: "8420 BCN", phone: "+34 622 456 789", netCost: 92, sellPrice: 138, margin: 33.3, status: "Confirmed", bookingDate: "2024-11-08", leadPax: "Hannah Briggs", email: "h.briggs@suntours.es", luggage: "4 large + 2 hand", notes: "" },
    { id: "TRF-12480", ref: "TRF-12480", agency: "Global Ventures Ltd", agencyId: 3, route: "LHR → Central London", origin: "Heathrow T5", dest: "The Dorchester Hotel", date: "2024-12-16", time: "10:15", pax: 2, vendor: "Welcome Pickups", driver: "Ahmed Hassan", vehicle: "Tesla Model S", plate: "LN18 ABC", phone: "+44 7700 123456", netCost: 68, sellPrice: 102, margin: 33.3, status: "In Progress", bookingDate: "2024-11-05", leadPax: "John Smith", email: "j.smith@globalventures.co.uk", luggage: "2 large", notes: "VIP client, English-speaking driver required" },
    { id: "TRF-12479", ref: "TRF-12479", agency: "Nordic Explorers", agencyId: 4, route: "ARN Airport → Stockholm City", origin: "Arlanda Airport", dest: "Grand Hôtel Stockholm", date: "2024-12-15", time: "18:45", pax: 2, vendor: "GetTransfer", driver: "Lars Andersson", vehicle: "Volvo V90", plate: "ABC 123", phone: "+46 70 123 4567", netCost: 54, sellPrice: 81, margin: 33.3, status: "Confirmed", bookingDate: "2024-11-02", leadPax: "Ingrid Svensson", email: "i.svensson@nordicexplorers.se", luggage: "2 medium", notes: "" },
    { id: "TRF-12478", ref: "TRF-12478", agency: "Optitron Travel", agencyId: 1, route: "Hotel → MAD Airport", origin: "Hotel Westin Palace", dest: "Madrid Barajas T4", date: "2024-12-22", time: "06:00", pax: 2, vendor: "Cabify Business", driver: "TBA", vehicle: "TBA", plate: "", phone: "", netCost: 42, sellPrice: 63, margin: 33.3, status: "Pending", bookingDate: "2024-11-18", leadPax: "Ryan Hou", email: "r.hou@optitron.com", luggage: "2 large", notes: "Early morning pickup, confirm driver 24h prior" },
    { id: "TRF-12477", ref: "TRF-12477", agency: "SunTours España", agencyId: 2, route: "Valencia City Tour (4h)", origin: "Hotel Caro", dest: "Roundtrip City Tour", date: "2024-12-14", time: "10:00", pax: 6, vendor: "HolidayTaxis", driver: "Miguel Torres", vehicle: "Mercedes Sprinter", plate: "4820 VLC", phone: "+34 633 567 890", netCost: 180, sellPrice: 270, margin: 33.3, status: "Confirmed", bookingDate: "2024-10-28", leadPax: "Ana García", email: "a.garcia@suntours.es", luggage: "0 (day tour)", notes: "City tour with English guide included" },
    { id: "TRF-12476", ref: "TRF-12476", agency: "Global Ventures Ltd", agencyId: 3, route: "CDG Airport → Paris Hotel", origin: "Charles de Gaulle T2", dest: "Le Bristol Paris", date: "2024-12-20", time: "12:30", pax: 3, vendor: "Blacklane", driver: "Pierre Dubois", vehicle: "BMW 7 Series", plate: "AB-123-CD", phone: "+33 6 12 34 56 78", netCost: 85, sellPrice: 128, margin: 33.5, status: "Confirmed", bookingDate: "2024-11-10", leadPax: "Sophie Martin", email: "s.martin@globalventures.fr", luggage: "3 large", notes: "" },
    { id: "TRF-12475", ref: "TRF-12475", agency: "Nordic Explorers", agencyId: 4, route: "CPH Airport → City Center", origin: "Copenhagen Kastrup", dest: "Hotel d'Angleterre", date: "2024-12-13", time: "14:00", pax: 4, vendor: "Cabify Business", driver: "Morten Nielsen", vehicle: "VW Multivan", plate: "XY 12 345", phone: "+45 20 12 34 56", netCost: 72, sellPrice: 108, margin: 33.3, status: "Cancelled", bookingDate: "2024-10-22", leadPax: "Erik Hansen", email: "e.hansen@nordicexplorers.dk", luggage: "4 large", notes: "Cancelled by client — full refund issued" },
  ];

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-head__title">Transfers</h1>
          <div className="page-head__sub">Manage all transfer bookings — airports, hotels, chauffeur services</div>
        </div>
        <div className="page-head__actions">
          <Button kind="secondary" icon={<Icon.Download />}>Export</Button>
          <Button kind="primary" icon={<Icon.Plus />} onClick={() => toast({ title: "Demo data - backend not wired", tone: "warning" })}>New booking</Button>
        </div>
      </div>

      <div className="grid grid--4" style={{ marginBottom: 18 }}>
        <Metric accent label="Active bookings" value="1,240" delta="+22% YoY" deltaDir="up" />
        <Metric label="Revenue (YTD)" value="€520k" hint="All vendors" />
        <Metric label="Avg margin" value="33.3%" hint="Net to sell" />
        <Metric label="Top vendor" value="Cabify" hint="€178k revenue" />
      </div>

      <div className="filter-bar">
        <input className="input" placeholder="Search ref, pax, route..." 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 vendors</option><option>Cabify Business</option><option>Blacklane</option><option>HolidayTaxis</option><option>Welcome Pickups</option><option>GetTransfer</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>
        <input className="input" type="date" />
        <span className="spacer" />
        <Button kind="ghost" size="sm" icon={<Icon.Filter />}>More filters</Button>
      </div>

      <Card flush>
        <table className="tbl">
          <thead>
            <tr>
              <th>Ref</th><th>Route</th><th>Date · Time</th><th>Pax</th><th>Agency</th><th>Vendor</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>
            {TRANSFERS.map((t) => (
              <tr key={t.id} onClick={() => onOpenDetail(t)} style={{ cursor: "pointer" }}>
                <td className="mono bold">{t.ref}</td>
                <td>
                  <div className="bold">{t.route}</div>
                  <div className="tiny muted">{t.origin} → {t.dest}</div>
                </td>
                <td className="mono">{t.date} · {t.time}</td>
                <td className="num mono">{t.pax}</td>
                <td className="muted">{t.agency}</td>
                <td>{t.vendor}</td>
                <td className="num mono">€{t.netCost}</td>
                <td className="num mono bold">€{t.sellPrice}</td>
                <td className="num mono" style={{ color: "var(--success)" }}>{t.margin.toFixed(1)}%</td>
                <td><TransferStatusBadge status={t.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 transfer", 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>

      <div style={{ marginTop: 18 }}>
        <Pager currentPage={page} totalPages={8} onPageChange={setPage} />
      </div>
    </div>
  );
}

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>;
}

// -----------------------------------------------------------
// TRANSFER DETAIL
// -----------------------------------------------------------
function TransferDetail({ transfer: t, onBack }) {
  const [tab, setTab] = useState_t("overview");

  return (
    <div>
      <div className="page-head">
        <div>
          <Button kind="ghost" icon={<Icon.ArrowLeft />} onClick={onBack}>Back to list</Button>
          <h1 className="page-head__title" style={{ marginTop: 8 }}>{t.ref} · {t.route}</h1>
          <div className="page-head__sub">{t.agency} · {t.date} at {t.time} · {t.pax} pax</div>
        </div>
        <div className="page-head__actions">
          <TransferStatusBadge status={t.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 transfer", body: "Refund will be processed.", tone: "danger" })}>Cancel booking</Button>
        </div>
      </div>

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

      {tab === "overview" && (
        <div className="grid" style={{ gridTemplateColumns: "1.4fr 1fr", gap: 18 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Card title="Route & Schedule">
              <div className="grid grid--2" style={{ gap: 14 }}>
                <Field label="Origin"><div className="read-only">{t.origin}</div></Field>
                <Field label="Destination"><div className="read-only">{t.dest}</div></Field>
                <Field label="Pickup date"><div className="read-only mono">{t.date}</div></Field>
                <Field label="Pickup time"><div className="read-only mono">{t.time}</div></Field>
                <Field label="Passengers"><div className="read-only mono">{t.pax}</div></Field>
                <Field label="Luggage"><div className="read-only">{t.luggage}</div></Field>
              </div>
            </Card>

            <Card title="Vendor & Driver">
              <div className="grid grid--2" style={{ gap: 14 }}>
                <Field label="Transfer vendor"><div className="read-only bold">{t.vendor}</div></Field>
                <Field label="Driver name"><div className="read-only">{t.driver || "TBA"}</div></Field>
                <Field label="Vehicle"><div className="read-only">{t.vehicle || "TBA"}</div></Field>
                <Field label="License plate"><div className="read-only mono">{t.plate || "—"}</div></Field>
                <Field label="Driver phone"><div className="read-only mono">{t.phone || "—"}</div></Field>
              </div>
            </Card>

            <Card title="Special requests & notes">
              <div className="read-only" style={{ minHeight: 60, whiteSpace: "pre-wrap" }}>
                {t.notes || "No special requests."}
              </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">{t.ref}</div></Field>
              <Field label="Booked on"><div className="read-only mono">{t.bookingDate}</div></Field>
              <Field label="Agency"><div className="read-only">{t.agency}</div></Field>
              <Field label="Status"><TransferStatusBadge status={t.status} /></Field>
            </Card>

            <Card title="Pricing">
              <div className="grid grid--2" style={{ gap: 12 }}>
                <Field label="Net cost"><div className="read-only mono">€{t.netCost.toFixed(2)}</div></Field>
                <Field label="Sell price"><div className="read-only mono bold">€{t.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)" }}>{t.margin.toFixed(1)}% (€{(t.sellPrice - t.netCost).toFixed(2)})</span>
              </div>
            </Card>

            <Card title="Lead passenger">
              <Field label="Name"><div className="read-only">{t.leadPax}</div></Field>
              <Field label="Email"><div className="read-only mono">{t.email}</div></Field>
            </Card>
          </div>
        </div>
      )}

      {tab === "pax" && (
        <Card title="Passenger details">
          <table className="tbl">
            <thead><tr><th>Name</th><th>Email</th><th>Phone</th><th>Type</th></tr></thead>
            <tbody>
              <tr><td className="bold">{t.leadPax}</td><td className="mono">{t.email}</td><td className="mono">+34 612 345 678</td><td><Badge tone="indigo">Lead pax</Badge></td></tr>
              {t.pax > 1 && <tr><td>Passenger 2</td><td className="mono">—</td><td className="mono">—</td><td><Badge>Companion</Badge></td></tr>}
              {t.pax > 2 && <tr><td>Passenger 3</td><td className="mono">—</td><td className="mono">—</td><td><Badge>Companion</Badge></td></tr>}
            </tbody>
          </table>
        </Card>
      )}

      {tab === "driver" && (
        <Card title="Driver & Vehicle information">
          <div className="grid grid--2" style={{ gap: 14 }}>
            <Field label="Driver name"><input className="input" defaultValue={t.driver || ""} placeholder="TBA" /></Field>
            <Field label="Driver phone"><input className="input" type="tel" defaultValue={t.phone || ""} placeholder="+34 600 000 000" /></Field>
            <Field label="Vehicle type"><input className="input" defaultValue={t.vehicle || ""} placeholder="Mercedes E-Class" /></Field>
            <Field label="License plate"><input className="input" defaultValue={t.plate || ""} placeholder="1234 ABC" /></Field>
          </div>
          <div style={{ marginTop: 14 }}>
            <Button kind="primary">Save changes</Button>
          </div>
        </Card>
      )}

      {tab === "pricing" && (
        <Card title="Pricing breakdown">
          <div className="grid grid--2" style={{ gap: 14 }}>
            <Field label="Net cost (from vendor)"><input className="input" type="number" defaultValue={t.netCost} step="0.01" /></Field>
            <Field label="Sell price (to agency)"><input className="input" type="number" defaultValue={t.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)" }}>{t.margin.toFixed(1)}% (€{(t.sellPrice - t.netCost).toFixed(2)})</span>
          </div>
          <div style={{ marginTop: 14 }}>
            <Button kind="primary">Update pricing</Button>
          </div>
        </Card>
      )}

      {tab === "notes" && (
        <div className="grid" style={{ gridTemplateColumns: "1.4fr 1fr", gap: 18 }}>
          <Card title="Internal notes">
            <Field label="Add note"><textarea className="textarea" rows={4} placeholder="Add internal note visible only to admin..." /></Field>
            <Button kind="primary" icon={<Icon.Plus />}>Add note</Button>
            <div className="divider" />
            <div className="timeline">
              <div className="timeline__item">
                <div className="timeline__dot" />
                <div className="timeline__content">
                  <div className="row" style={{ justifyContent: "space-between", marginBottom: 4 }}>
                    <span className="bold">Ryan Hou</span>
                    <span className="tiny muted mono">2024-11-18 14:20</span>
                  </div>
                  <div className="muted">{t.notes || "Booking confirmed with vendor."}</div>
                </div>
              </div>
            </div>
          </Card>

          <Card title="Booking timeline">
            <div className="timeline">
              <div className="timeline__item">
                <div className="timeline__dot" style={{ background: "var(--success)" }} />
                <div className="timeline__content">
                  <div className="bold">Booking created</div>
                  <div className="tiny muted mono">{t.bookingDate} 10:42</div>
                </div>
              </div>
              <div className="timeline__item">
                <div className="timeline__dot" style={{ background: "var(--success)" }} />
                <div className="timeline__content">
                  <div className="bold">Confirmed by {t.vendor}</div>
                  <div className="tiny muted mono">{t.bookingDate} 11:18</div>
                </div>
              </div>
              {t.driver && (
                <div className="timeline__item">
                  <div className="timeline__dot" style={{ background: "var(--info)" }} />
                  <div className="timeline__content">
                    <div className="bold">Driver assigned</div>
                    <div className="tiny muted">{t.driver} · {t.vehicle}</div>
                  </div>
                </div>
              )}
            </div>
          </Card>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PageTransfers });
