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

// ============================================================
// PAGE: VIP LOUNGE — list + detail
// ============================================================
function PageVIPLounge({ onNav }) {
  const [view, setView] = useState_vl("list");
  const [selected, setSelected] = useState_vl(null);

  const openDetail = (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> Airport Lounge backend is not yet wired — all bookings and KPIs below are mocks. Do not act on this data.</span>
      </div>
      {view === "list"
        ? <VIPLoungeList onOpenDetail={openDetail} />
        : <VIPLoungeDetail booking={selected} onBack={backToList} />}
    </div>
  );
}

// -----------------------------------------------------------
// VIP LOUNGE LIST
// -----------------------------------------------------------
function VIPLoungeList({ onOpenDetail }) {
  const BOOKINGS = [
    { id: "VL-12482", ref: "VL-12482", agency: "Optitron Travel", airport: "MAD", lounge: "Plaza Premium Lounge", terminal: "T4", date: "2024-12-18", time: "14:30", pax: 2, vendor: "Plaza Premium", netCost: 48, sellPrice: 72, margin: 33.3, status: "Confirmed", bookingDate: "2024-11-12", leadPax: "Maria Lopez", email: "maria.lopez@optitron.com", services: "Food & beverages, Showers, Wi-Fi", accessDuration: "3 hours" },
    { id: "VL-12481", ref: "VL-12481", agency: "SunTours España", airport: "BCN", lounge: "Sala VIP Colomer", terminal: "T1", date: "2024-12-17", time: "16:00", pax: 4, vendor: "Priority Pass", netCost: 92, sellPrice: 138, margin: 33.3, status: "Confirmed", bookingDate: "2024-11-08", leadPax: "Hannah Briggs", email: "h.briggs@suntours.es", services: "Food & beverages, Wi-Fi, Press", accessDuration: "2 hours" },
    { id: "VL-12480", ref: "VL-12480", agency: "Global Ventures Ltd", airport: "LHR", lounge: "No1 Lounge", terminal: "T5", date: "2024-12-16", time: "10:15", pax: 3, vendor: "LoungeKey", netCost: 105, sellPrice: 158, margin: 33.5, status: "In Progress", bookingDate: "2024-11-05", leadPax: "John Smith", email: "j.smith@globalventures.co.uk", services: "Full service bar, Hot meals, Showers, Wi-Fi", accessDuration: "4 hours" },
    { id: "VL-12479", ref: "VL-12479", agency: "Nordic Explorers", airport: "ARN", lounge: "SAS Lounge", terminal: "5", date: "2024-12-15", time: "18:45", pax: 2, vendor: "SAS", netCost: 68, sellPrice: 102, margin: 33.3, status: "Confirmed", bookingDate: "2024-11-02", leadPax: "Ingrid Svensson", email: "i.svensson@nordicexplorers.se", services: "Scandinavian cuisine, Bar, Wi-Fi", accessDuration: "2 hours" },
    { id: "VL-12478", ref: "VL-12478", agency: "Optitron Travel", airport: "MAD", lounge: "Cibeles Lounge", terminal: "T4", date: "2024-12-22", time: "06:00", pax: 1, vendor: "Plaza Premium", netCost: 38, sellPrice: 57, margin: 33.3, status: "Pending", bookingDate: "2024-11-18", leadPax: "Ryan Hou", email: "r.hou@optitron.com", services: "Light snacks, Wi-Fi", accessDuration: "1.5 hours" },
    { id: "VL-12477", ref: "VL-12477", agency: "SunTours España", airport: "BCN", lounge: "Pau Casals VIP Lounge", terminal: "T1", date: "2024-12-14", time: "10:00", pax: 6, vendor: "Priority Pass", netCost: 180, sellPrice: 270, margin: 33.3, status: "Confirmed", bookingDate: "2024-10-28", leadPax: "Ana García", email: "a.garcia@suntours.es", services: "Full buffet, Bar, Showers, Wi-Fi, Family area", accessDuration: "3 hours" },
    { id: "VL-12476", ref: "VL-12476", agency: "Global Ventures Ltd", airport: "CDG", lounge: "Air France La Première Lounge", terminal: "2E", date: "2024-12-20", time: "12:30", pax: 2, vendor: "Priority Pass", netCost: 140, sellPrice: 210, margin: 33.3, status: "Confirmed", bookingDate: "2024-11-10", leadPax: "Sophie Martin", email: "s.martin@globalventures.fr", services: "Fine dining, Champagne bar, Spa, Showers, Wi-Fi", accessDuration: "4 hours" },
    { id: "VL-12475", ref: "VL-12475", agency: "Nordic Explorers", airport: "CPH", lounge: "Copenhagen Aspire Lounge", terminal: "3", date: "2024-12-13", time: "14:00", pax: 3, vendor: "LoungeKey", netCost: 84, sellPrice: 126, margin: 33.3, status: "Cancelled", bookingDate: "2024-10-22", leadPax: "Erik Hansen", email: "e.hansen@nordicexplorers.dk", services: "Food & beverages, Wi-Fi", accessDuration: "2 hours" },
  ];

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-head__title">Airport Lounge</h1>
          <div className="page-head__sub">Manage airport lounge access bookings</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="384" delta="+17% YoY" deltaDir="up" />
        <Metric label="Revenue (YTD)" value="€180k" hint="All vendors" />
        <Metric label="Avg margin" value="33.3%" hint="Net to sell" />
        <Metric label="Top lounge" value="Plaza Premium" hint="€68k revenue" />
      </div>

      <div className="filter-bar">
        <input className="input" placeholder="Search ref, pax, airport..." 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 airports</option><option>MAD</option><option>BCN</option><option>LHR</option><option>CDG</option><option>ARN</option><option>CPH</option></select>
        <select className="select"><option>All vendors</option><option>Plaza Premium</option><option>Priority Pass</option><option>LoungeKey</option><option>SAS</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="ghost" size="sm" icon={<Icon.Filter />}>More filters</Button>
      </div>

      <Card flush>
        <table className="tbl">
          <thead>
            <tr>
              <th>Ref</th><th>Airport · Lounge</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>
            {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.airport} · {b.lounge}</div>
                  <div className="tiny muted">Terminal {b.terminal}</div>
                </td>
                <td className="mono">{b.date} · {b.time}</td>
                <td className="num mono">{b.pax}</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><VIPStatusBadge 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 booking", 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>
  );
}

function VIPStatusBadge({ 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>;
}

// -----------------------------------------------------------
// VIP LOUNGE DETAIL
// -----------------------------------------------------------
function VIPLoungeDetail({ booking: b, onBack }) {
  const [tab, setTab] = useState_vl("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 }}>{b.ref} · {b.airport} {b.lounge}</h1>
          <div className="page-head__sub">{b.agency} · {b.date} at {b.time} · {b.pax} pax</div>
        </div>
        <div className="page-head__actions">
          <VIPStatusBadge 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: "pax",      label: "Passengers" },
        { 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="Lounge access details">
              <div className="grid grid--2" style={{ gap: 14 }}>
                <Field label="Airport"><div className="read-only mono bold">{b.airport}</div></Field>
                <Field label="Terminal"><div className="read-only mono">{b.terminal}</div></Field>
                <Field label="Lounge name"><div className="read-only bold">{b.lounge}</div></Field>
                <Field label="Vendor"><div className="read-only">{b.vendor}</div></Field>
                <Field label="Access date"><div className="read-only mono">{b.date}</div></Field>
                <Field label="Access time"><div className="read-only mono">{b.time}</div></Field>
                <Field label="Duration"><div className="read-only">{b.accessDuration}</div></Field>
                <Field label="Passengers"><div className="read-only mono">{b.pax}</div></Field>
              </div>
            </Card>

            <Card title="Services included">
              <div className="read-only" style={{ minHeight: 60, whiteSpace: "pre-wrap" }}>
                {b.services}
              </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"><VIPStatusBadge 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="Lead passenger">
              <Field label="Name"><div className="read-only">{b.leadPax}</div></Field>
              <Field label="Email"><div className="read-only mono">{b.email}</div></Field>
            </Card>
          </div>
        </div>
      )}

      {tab === "pax" && (
        <Card title="Passenger list">
          <table className="tbl">
            <thead><tr><th>Name</th><th>Email</th><th>Phone</th><th>Type</th></tr></thead>
            <tbody>
              <tr><td className="bold">{b.leadPax}</td><td className="mono">{b.email}</td><td className="mono">+34 612 345 678</td><td><Badge tone="indigo">Lead pax</Badge></td></tr>
              {b.pax > 1 && <tr><td>Passenger 2</td><td className="mono">—</td><td className="mono">—</td><td><Badge>Companion</Badge></td></tr>}
              {b.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 === "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={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>
  );
}

Object.assign(window, { PageVIPLounge });
