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

var { useState, useMemo } = React;

// ============================================================
// PAGE: DASHBOARD (Overview)
// ============================================================
function PageDashboard({ onNav }) {
  const [range, setRange] = useState("12m");
  const [compare, setCompare] = useState("2023");
  const [groupFilter, setGroupFilter] = useState("");
  const [marketFilter, setMarketFilter] = useState("");
  const [agencyFilter, setAgencyFilter] = useState("");
  const [managerFilter, setManagerFilter] = useState("");
  const [sectorFilter, setSectorFilter] = useState("");

  // Revenue overview by service
  const revenue = [
    { label: "Jan", accommodation: 28000, transfer: 9200,  car: 11800 },
    { label: "Feb", accommodation: 31000, transfer: 10100, car: 12400 },
    { label: "Mar", accommodation: 36400, transfer: 11250, car: 14200 },
    { label: "Apr", accommodation: 42100, transfer: 12500, car: 16800 },
    { label: "May", accommodation: 48800, transfer: 13900, car: 18500 },
    { label: "Jun", accommodation: 54200, transfer: 14800, car: 21000 },
    { label: "Jul", accommodation: 61400, transfer: 16200, car: 23900 },
    { label: "Aug", accommodation: 65800, transfer: 17600, car: 25400 },
    { label: "Sep", accommodation: 57200, transfer: 15400, car: 22100 },
    { label: "Oct", accommodation: 48400, transfer: 13800, car: 19200 },
    { label: "Nov", accommodation: 41100, transfer: 12700, car: 17500 },
    { label: "Dec", accommodation: 39400, transfer: 12200, car: 17000 },
  ];

  // Booking detail (line)
  const bookingTrend = [
    { label: "Jan", accom: 320, transfer: 110, car: 175 },
    { label: "Feb", accom: 380, transfer: 130, car: 200 },
    { label: "Mar", accom: 410, transfer: 140, car: 220 },
    { label: "Apr", accom: 470, transfer: 160, car: 250 },
    { label: "May", accom: 540, transfer: 175, car: 290 },
    { label: "Jun", accom: 590, transfer: 195, car: 330 },
    { label: "Jul", accom: 650, transfer: 220, car: 360 },
    { label: "Aug", accom: 670, transfer: 235, car: 390 },
    { label: "Sep", accom: 580, transfer: 210, car: 340 },
    { label: "Oct", accom: 510, transfer: 190, car: 300 },
    { label: "Nov", accom: 430, transfer: 165, car: 270 },
    { label: "Dec", accom: 420, transfer: 160, car: 265 },
  ];

  const searchVol = [
    { label: "Jan", thisYear: 12400, lastYear: 10100 },
    { label: "Feb", thisYear: 13900, lastYear: 11800 },
    { label: "Mar", thisYear: 17200, lastYear: 13600 },
    { label: "Apr", thisYear: 19800, lastYear: 16100 },
    { label: "May", thisYear: 23400, lastYear: 17800 },
    { label: "Jun", thisYear: 28100, lastYear: 22300 },
    { label: "Jul", thisYear: 32600, lastYear: 26500 },
    { label: "Aug", thisYear: 34200, lastYear: 27200 },
    { label: "Sep", thisYear: 27400, lastYear: 21100 },
    { label: "Oct", thisYear: 22600, lastYear: 17400 },
    { label: "Nov", thisYear: 19000, lastYear: 14200 },
    { label: "Dec", thisYear: 16800, lastYear: 13100 },
  ];

  const conversion = [
    { label: "Jan", rate: 2.6 }, { label: "Feb", rate: 2.8 }, { label: "Mar", rate: 3.1 },
    { label: "Apr", rate: 3.4 }, { label: "May", rate: 3.5 }, { label: "Jun", rate: 3.8 },
    { label: "Jul", rate: 4.1 }, { label: "Aug", rate: 4.2 }, { label: "Sep", rate: 3.7 },
    { label: "Oct", rate: 3.4 }, { label: "Nov", rate: 3.1 }, { label: "Dec", rate: 2.9 },
  ];

  const fmtEUR = (v) => "€" + (v >= 1000 ? (v / 1000).toFixed(v >= 10000 ? 0 : 1) + "k" : v);

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-head__title">Report Overview</h1>
          <div className="page-head__sub">Performance, revenue and booking analytics across all markets.</div>
        </div>
        <div className="page-head__actions">
          <select className="select" value={groupFilter} onChange={(e) => setGroupFilter(e.target.value)} style={{ minWidth: 180 }}>
            <option value="">All travel groups</option>
            {(window.MOCK.TRAVEL_GROUPS || []).map((g) => <option key={g.id}>{g.name}</option>)}
          </select>
          <Segmented value={range} onChange={setRange} options={[
            { value: "7d", label: "7d" }, { value: "30d", label: "30d" },
            { value: "12m", label: "12m" }, { value: "ytd", label: "YTD" },
          ]} />
          <Button kind="secondary" icon={<Icon.Cal />}>Oct 1 – Dec 31, 2024</Button>
          <Button kind="secondary" icon={<Icon.Download />}>Export</Button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="grid grid--4" style={{ marginBottom: 18 }}>
        <Metric accent label={<><Icon.Trend size={14} /> Total Revenue</>} value="€612,400" delta="12.4% vs LY" deltaDir="up" />
        <Metric label={<><Icon.Bookings size={14} /> Total Bookings</>} value="9,182" delta="8.1% vs LY" deltaDir="up" />
        <Metric label={<><Icon.Pie size={14} /> Conversion Rate</>} value="3.42%" delta="0.4 pt" deltaDir="up" />
        <Metric label={<><Icon.Warning size={14} /> Unpaid Orders</>} value="€43,715" delta="-15.7% vs LM" deltaDir="down" hint="216 total" />
      </div>

      {/* Revenue + Booking detail */}
      <div className="grid" style={{ gridTemplateColumns: "2fr 1fr", marginBottom: 18 }}>
        <Card
          title="Revenue overview"
          sub="Revenue by service type across the year"
          actions={
            <>
              <div className="chart-legend">
                <span className="chart-legend__item"><span className="chart-legend__sw" style={{ background: "#635bff" }} />Accommodation</span>
                <span className="chart-legend__item"><span className="chart-legend__sw" style={{ background: "#00d4ff" }} />Transfer</span>
                <span className="chart-legend__item"><span className="chart-legend__sw" style={{ background: "#0e7c66" }} />Rental Car</span>
              </div>
            </>
          }
        >
          <BarChart
            stacked
            height={260}
            valueFmt={fmtEUR}
            data={revenue}
            series={[
              { key: "accommodation", name: "Accommodation", color: "#635bff" },
              { key: "transfer",      name: "Transfer",      color: "#00d4ff" },
              { key: "car",           name: "Rental Car",    color: "#0e7c66" },
            ]}
          />
        </Card>
        <Card title="Payment information" sub="Year-to-date">
          <div style={{ display: "flex", justifyContent: "center", marginBottom: 10 }}>
            <DonutCard
              total="€539k"
              totalLabel="Total"
              data={[
                { label: "Payment received", value: 408000, color: "#635bff" },
                { label: "Refunded amount",  value: 56000,  color: "#ff9f43" },
                { label: "Customer payment", value: 75000,  color: "#0e7c66" },
              ]}
            />
          </div>
        </Card>
      </div>

      {/* Financial / System / Bookings row */}
      <div className="grid grid--3" style={{ marginBottom: 18 }}>
        <Card title="Financial information">
          <div className="grid grid--2" style={{ gap: 12 }}>
            <KvBox label="Unpaid orders" value="€43,715" hint="Total: €120,000" />
            <KvBox label="Refundable" value="€11,920" hint="Total: €28,440" />
            <KvBox label="Booking volume" value="€392,150" hint="9,182 bookings" />
            <KvBox label="Booked %" value="76.5%" hint="Of all sessions" deltaDir="up" delta="1.4 pt" />
          </div>
        </Card>
        <Card title="System health" sub="Last 24h">
          <div className="grid grid--2" style={{ gap: 12 }}>
            <KvBox label="Uptime" value="9h 30m" hint="Without downtime" tone="success" />
            <KvBox label="Errors" value="10" hint="Unsolved" tone="danger" />
            <KvBox label="API latency" value="142 ms" hint="P95" />
            <KvBox label="Active sessions" value="1,408" hint="Right now" />
          </div>
        </Card>
        <Card title="Booking overview" sub="By status">
          <div style={{ display: "grid", gap: 14 }}>
            <StatRow label="Confirmed" value="6,210" pct={68} color="#0e7c66" />
            <StatRow label="On hold"   value="1,840" pct={20} color="#ff9f43" />
            <StatRow label="Cancelled" value="730"   pct={8}  color="#d4366a" />
            <StatRow label="Rebooked"  value="402"   pct={4}  color="#635bff" />
          </div>
        </Card>
      </div>

      {/* Booking profile + Profit/loss */}
      <div className="grid" style={{ gridTemplateColumns: "1.5fr 1fr", marginBottom: 18 }}>
        <Card
          title="Booking profile"
          sub="Bookings by service type"
          actions={<Segmented value="m" onChange={() => {}} options={[
            { value: "w", label: "Week" }, { value: "m", label: "Month" }, { value: "y", label: "Year" },
          ]} />}
        >
          <AreaChart
            data={bookingTrend}
            height={260}
            series={[
              { key: "accom",    name: "Accommodation", color: "#635bff" },
              { key: "transfer", name: "Transfer",      color: "#00d4ff" },
              { key: "car",      name: "Rental Car",    color: "#0e7c66" },
            ]}
          />
        </Card>
        <Card title="Profit / loss" sub="By service category">
          <table className="tbl">
            <thead>
              <tr><th>Category</th><th className="num">Revenue</th><th className="num">Cost</th><th className="num">Profit</th></tr>
            </thead>
            <tbody>
              <tr><td><Tag kind="hotel">Accommodation</Tag></td><td className="num mono">€485k</td><td className="num mono">€340k</td><td className="num mono" style={{ color: "var(--success)" }}>€145k</td></tr>
              <tr><td><Tag kind="rental">Rental Cars</Tag></td><td className="num mono">€212k</td><td className="num mono">€158k</td><td className="num mono" style={{ color: "var(--success)" }}>€54k</td></tr>
              <tr><td><Tag kind="transfer">Transfer</Tag></td><td className="num mono">€155k</td><td className="num mono">€121k</td><td className="num mono" style={{ color: "var(--success)" }}>€34k</td></tr>
              <tr><td><Tag kind="flight">Flight</Tag></td><td className="num mono">€89k</td><td className="num mono">€95k</td><td className="num mono" style={{ color: "var(--danger)" }}>−€6k</td></tr>
              <tr style={{ background: "var(--bg-subtle)" }}>
                <td className="bold">Total</td>
                <td className="num mono bold">€941k</td>
                <td className="num mono bold">€714k</td>
                <td className="num mono bold" style={{ color: "var(--success)" }}>€227k</td>
              </tr>
            </tbody>
          </table>
        </Card>
      </div>

      {/* Booking channel + Search volume */}
      <div className="grid" style={{ gridTemplateColumns: "1fr 1.6fr", marginBottom: 18 }}>
        <Card title="Booking channel" sub="Web vs API">
          <DonutCard
            data={[
              { label: "Web", value: 6420, color: "#635bff" },
              { label: "API", value: 2762, color: "#00d4ff" },
              { label: "Phone", value: 612, color: "#0e7c66" },
            ]}
          />
          <div className="divider" />
          <table className="tbl" style={{ fontSize: 12.5 }}>
            <thead><tr><th>Rank</th><th>Source</th><th className="num">Bookings</th></tr></thead>
            <tbody>
              <tr><td>1</td><td>trekko.com</td><td className="num mono">4,182</td></tr>
              <tr><td>2</td><td>Agency portal</td><td className="num mono">2,238</td></tr>
              <tr><td>3</td><td>Public API</td><td className="num mono">2,762</td></tr>
            </tbody>
          </table>
        </Card>
        <Card title="Search volume" sub="Compared to last year" actions={<Segmented value="m" onChange={() => {}} options={[{value:"w",label:"Week"},{value:"m",label:"Month"},{value:"y",label:"Year"}]} />}>
          <AreaChart
            data={searchVol}
            height={240}
            valueFmt={(v) => v >= 1000 ? (v/1000).toFixed(0) + "k" : v}
            series={[
              { key: "thisYear", name: "This year", color: "#635bff" },
              { key: "lastYear", name: "Last year", color: "#a78bfa" },
            ]}
          />
        </Card>
      </div>

      {/* All booking progress + Conversion */}
      <div className="grid" style={{ gridTemplateColumns: "1fr 1.6fr", marginBottom: 18 }}>
        <Card title="All booking progress">
          <BarChart
            data={[
              { label: "Q1", booked: 1110, cancelled: 92 },
              { label: "Q2", booked: 1640, cancelled: 130 },
              { label: "Q3", booked: 1990, cancelled: 184 },
              { label: "Q4", booked: 1320, cancelled: 110 },
            ]}
            height={200}
            series={[
              { key: "booked",    name: "Booked",    color: "#635bff" },
              { key: "cancelled", name: "Cancelled", color: "#d4366a" },
            ]}
          />
        </Card>
        <Card title="Conversion rate (search → booking)" actions={<Segmented value="y" onChange={() => {}} options={[{value:"m",label:"Month"},{value:"q",label:"Quarter"},{value:"y",label:"Year"}]} />}>
          <AreaChart
            data={conversion}
            height={200}
            valueFmt={(v) => v + "%"}
            series={[{ key: "rate", name: "Conversion", color: "#635bff" }]}
          />
        </Card>
      </div>

      {/* Travel agency insights */}
      <h3 style={{ fontSize: 16, fontWeight: 600, margin: "26px 0 12px", color: "var(--ink-1)" }}>Travel agency insights</h3>
      <div className="grid grid--3" style={{ marginBottom: 18 }}>
        <Card title="Top revenue agencies" flush>
          <table className="tbl">
            <thead><tr><th>#</th><th>Agency</th><th className="num">Bookings</th><th className="num">Revenue</th></tr></thead>
            <tbody>
              {window.MOCK.TRAVEL_AGENCIES.slice(0, 5).sort((a,b)=>b.sales-a.sales).map((a, i) => (
                <tr key={a.id}><td className="muted">{i+1}</td><td>{a.name}</td><td className="num mono">{a.bookings}</td><td className="num mono">€{a.sales.toLocaleString()}</td></tr>
              ))}
            </tbody>
          </table>
        </Card>
        <Card title="Top lost agencies" flush>
          <table className="tbl">
            <thead><tr><th>#</th><th>Agency</th><th className="num">Last 30d</th></tr></thead>
            <tbody>
              <tr><td className="muted">1</td><td>Northwind Travel</td><td className="num mono" style={{ color: "var(--danger)" }}>−42</td></tr>
              <tr><td className="muted">2</td><td>StrideBrite</td><td className="num mono" style={{ color: "var(--danger)" }}>−18</td></tr>
              <tr><td className="muted">3</td><td>Bluewave Holdings</td><td className="num mono" style={{ color: "var(--danger)" }}>−11</td></tr>
              <tr><td className="muted">4</td><td>Drive Athens</td><td className="num mono" style={{ color: "var(--danger)" }}>−7</td></tr>
              <tr><td className="muted">5</td><td>AC Hotels Group</td><td className="num mono" style={{ color: "var(--danger)" }}>−4</td></tr>
            </tbody>
          </table>
        </Card>
        <Card title="Top growth agencies" flush>
          <table className="tbl">
            <thead><tr><th>#</th><th>Agency</th><th className="num">Δ Bookings</th></tr></thead>
            <tbody>
              <tr><td className="muted">1</td><td>OptiTron Tech</td><td className="num mono" style={{ color: "var(--success)" }}>+58</td></tr>
              <tr><td className="muted">2</td><td>Industrial Dynamics</td><td className="num mono" style={{ color: "var(--success)" }}>+47</td></tr>
              <tr><td className="muted">3</td><td>Paramount Products</td><td className="num mono" style={{ color: "var(--success)" }}>+33</td></tr>
              <tr><td className="muted">4</td><td>Aurora Routes</td><td className="num mono" style={{ color: "var(--success)" }}>+22</td></tr>
              <tr><td className="muted">5</td><td>Pacific Horizons</td><td className="num mono" style={{ color: "var(--success)" }}>+15</td></tr>
            </tbody>
          </table>
        </Card>
      </div>

      <Card title="Agency growth" sub="Comparison: this year vs last year">
        <AreaChart
          data={[
            { label: "Jan", current: 24, previous: 22 },
            { label: "Feb", current: 35, previous: 30 },
            { label: "Mar", current: 41, previous: 36 },
            { label: "Apr", current: 8,  previous: 18 },
            { label: "May", current: 28, previous: 26 },
            { label: "Jun", current: 40, previous: 38 },
            { label: "Jul", current: 72, previous: 60 },
            { label: "Aug", current: 88, previous: 71 },
            { label: "Sep", current: 60, previous: 55 },
            { label: "Oct", current: 78, previous: 64 },
            { label: "Nov", current: 92, previous: 73 },
            { label: "Dec", current: 41, previous: 36 },
          ]}
          height={260}
          series={[
            { key: "current",  name: "This year", color: "#635bff" },
            { key: "previous", name: "Last year", color: "#a78bfa" },
          ]}
        />
      </Card>

      {/* Product-specific insights */}
      <h3 style={{ fontSize: 16, fontWeight: 600, margin: "26px 0 12px", color: "var(--ink-1)" }}>Product-specific insights</h3>
      <ProductBlock
        title="Accommodation"
        bookings={[
          { label: "Jan", thisYear: 86, lastYear: 70 }, { label: "Feb", thisYear: 95, lastYear: 80 },
          { label: "Mar", thisYear: 110, lastYear: 88 }, { label: "Apr", thisYear: 125, lastYear: 100 },
          { label: "May", thisYear: 140, lastYear: 115 }, { label: "Jun", thisYear: 165, lastYear: 130 },
          { label: "Jul", thisYear: 178, lastYear: 145 }, { label: "Aug", thisYear: 184, lastYear: 156 },
          { label: "Sep", thisYear: 152, lastYear: 130 }, { label: "Oct", thisYear: 134, lastYear: 113 },
          { label: "Nov", thisYear: 118, lastYear: 95 },  { label: "Dec", thisYear: 110, lastYear: 89 },
        ]}
        rows={[
          { name: "Marriott International", trips: 482,   rating: 4.7, category: "Hotel", type: "Resort", price: "€189" },
          { name: "AC Hotels Group",         trips: 308,   rating: 4.4, category: "Hotel", type: "City",   price: "€142" },
          { name: "Hilton Worldwide",        trips: 264,   rating: 4.6, category: "Hotel", type: "Resort", price: "€212" },
        ]}
      />
      <div style={{ height: 16 }} />
      <ProductBlock
        title="Car Rental"
        bookings={[
          { label: "Jan", thisYear: 56, lastYear: 49 }, { label: "Feb", thisYear: 64, lastYear: 55 },
          { label: "Mar", thisYear: 78, lastYear: 65 }, { label: "Apr", thisYear: 92, lastYear: 78 },
          { label: "May", thisYear: 105, lastYear: 88 }, { label: "Jun", thisYear: 122, lastYear: 99 },
          { label: "Jul", thisYear: 134, lastYear: 110 }, { label: "Aug", thisYear: 142, lastYear: 118 },
          { label: "Sep", thisYear: 121, lastYear: 99 }, { label: "Oct", thisYear: 103, lastYear: 84 },
          { label: "Nov", thisYear: 92, lastYear: 73 },  { label: "Dec", thisYear: 86, lastYear: 68 },
        ]}
        rows={[
          { name: "Europcar Mobility Group", trips: 1102, rating: 4.4, category: "Rental", type: "Economy", price: "€38/d" },
          { name: "Sixt Rent a Car",          trips: 892,  rating: 4.5, category: "Rental", type: "Premium", price: "€72/d" },
          { name: "Hertz",                    trips: 805,  rating: 4.6, category: "Rental", type: "Mid",     price: "€55/d" },
        ]}
      />
      <div style={{ height: 16 }} />
      <ProductBlock
        title="Transfer"
        bookings={[
          { label: "Jan", thisYear: 28, lastYear: 25 }, { label: "Feb", thisYear: 31, lastYear: 27 },
          { label: "Mar", thisYear: 37, lastYear: 30 }, { label: "Apr", thisYear: 41, lastYear: 35 },
          { label: "May", thisYear: 47, lastYear: 39 }, { label: "Jun", thisYear: 53, lastYear: 44 },
          { label: "Jul", thisYear: 59, lastYear: 47 }, { label: "Aug", thisYear: 62, lastYear: 51 },
          { label: "Sep", thisYear: 52, lastYear: 42 }, { label: "Oct", thisYear: 47, lastYear: 38 },
          { label: "Nov", thisYear: 41, lastYear: 34 }, { label: "Dec", thisYear: 38, lastYear: 32 },
        ]}
        rows={[
          { name: "Eurostar Group", trips: 412, rating: 4.5, category: "Transfer", type: "Rail",  price: "€55" },
          { name: "Olympia Tours",  trips: 286, rating: 4.8, category: "Transfer", type: "Coach", price: "€32" },
          { name: "Costa Cruises",  trips: 144, rating: 4.3, category: "Transfer", type: "Ferry", price: "€78" },
        ]}
      />
    </div>
  );
}

// small helpers used in the dashboard
function KvBox({ label, value, hint, tone, delta, deltaDir }) {
  const toneCss = tone === "success" ? "var(--success)" : tone === "danger" ? "var(--danger)" : "var(--ink-1)";
  return (
    <div style={{ padding: "10px 12px", background: "var(--bg-subtle)", borderRadius: 8 }}>
      <div className="tiny muted">{label}</div>
      <div style={{ fontSize: 18, fontWeight: 600, color: toneCss, letterSpacing: "-0.01em", marginTop: 2 }}>{value}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
        {delta && <span className={`metric__delta metric__delta--${deltaDir || "up"}`}>{delta}</span>}
        {hint && <span className="tiny muted">{hint}</span>}
      </div>
    </div>
  );
}

function StatRow({ label, value, pct, color }) {
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
        <span style={{ fontSize: 13, color: "var(--ink-2)" }}>{label}</span>
        <span className="tabular bold">{value}</span>
      </div>
      <ProgressBar value={pct} color={color} />
      <div className="tiny muted" style={{ marginTop: 4 }}>{pct}% of total</div>
    </div>
  );
}

function ProductBlock({ title, bookings, rows }) {
  return (
    <Card title={title}>
      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
        <div>
          <div className="card__title" style={{ fontSize: 13, marginBottom: 8 }}>Total amount of booking</div>
          <BarChart
            data={bookings}
            height={160}
            series={[
              { key: "thisYear", name: "This year", color: "#635bff" },
              { key: "lastYear", name: "Last year", color: "#c1c9d2" },
            ]}
          />
        </div>
        <div>
          <div className="card__title" style={{ fontSize: 13, marginBottom: 8 }}>Total bookings</div>
          <BarChart
            data={bookings}
            height={160}
            series={[
              { key: "thisYear", name: "This year", color: "#00d4ff" },
              { key: "lastYear", name: "Last year", color: "#c1c9d2" },
            ]}
          />
        </div>
      </div>
      <table className="tbl">
        <thead>
          <tr><th>Vendor name</th><th className="num">Total trips</th><th>Rating</th><th>Category</th><th>Type</th><th className="num">Price</th></tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr key={r.name}>
              <td>{r.name}</td>
              <td className="num mono">{r.trips.toLocaleString()}</td>
              <td><span style={{ color: "#ff9f43" }}>{"★".repeat(Math.round(r.rating))}</span> <span className="tiny muted">({r.rating})</span></td>
              <td>{r.category}</td>
              <td>{r.type}</td>
              <td className="num mono">{r.price}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

// ============================================================
// PAGE: SALES MANAGER
// ============================================================
function PageSales() {
  const [manager, setManager] = useState("John Doe");
  const [monthly, setMonthly] = useState(220000);
  const [quarterly, setQuarterly] = useState(660000);
  const [yearly, setYearly] = useState(2640000);

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-head__title">Sales Manager Dashboard</h1>
          <div className="page-head__sub">Assign KPIs and track sales manager performance across products and markets.</div>
        </div>
        <div className="page-head__actions">
          <Button kind="secondary" icon={<Icon.Download />}>Export</Button>
          <Button kind="primary" icon={<Icon.Plus />}>New manager</Button>
        </div>
      </div>

      <Tabs
        tabs={[{ id: "ov", label: "Overview" }, { id: "mgr", label: "Sale Manager" }]}
        active="mgr"
        onChange={() => {}}
      />

      <Card title="KPI Assignment" sub="Set targets for the selected sales manager">
        <div className="grid grid--4" style={{ gap: 14 }}>
          <Field label="Sale Manager">
            <select className="select" value={manager} onChange={(e) => setManager(e.target.value)}>
              <option>John Doe</option><option>Maria Lopez</option><option>Ryan Hou</option><option>Hannah Briggs</option>
            </select>
          </Field>
          <Field label="Monthly Target (€)">
            <input className="input" type="number" value={monthly} onChange={(e) => setMonthly(+e.target.value)} />
          </Field>
          <Field label="Quarterly Target (€)">
            <input className="input" type="number" value={quarterly} onChange={(e) => setQuarterly(+e.target.value)} />
          </Field>
          <Field label="Yearly Target (€)">
            <input className="input" type="number" value={yearly} onChange={(e) => setYearly(+e.target.value)} />
          </Field>
        </div>
        <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
          <Button kind="primary">Save targets</Button>
          <Button kind="ghost">Reset</Button>
        </div>
      </Card>

      <div style={{ height: 18 }} />

      <Card title="KPI Progress" sub={`Current attainment vs. assigned target for ${manager}`}>
        <div className="grid grid--3" style={{ gap: 24 }}>
          <KpiProgress label="KPI Monthly"   value={72} actual="€152k" target="€220k" color="#00d4ff" />
          <KpiProgress label="KPI Quarterly" value={68} actual="€448k" target="€660k" color="#635bff" />
          <KpiProgress label="KPI Yearly"    value={55} actual="€1.45M" target="€2.64M" color="#ff9f43" />
        </div>
      </Card>

      <div style={{ height: 18 }} />

      <Card title="Sale Manager Performance" flush>
        <table className="tbl">
          <thead>
            <tr>
              <th>Sale manager</th>
              <th className="num">Agencies</th>
              <th className="num">Total Sales (€)</th>
              <th className="num">Room Nights</th>
              <th className="num">Transfers</th>
              <th className="num">Hotels</th>
              <th className="num">Rental Cars</th>
              <th className="num">vs Last year</th>
            </tr>
          </thead>
          <tbody>
            {[
              { name: "Ryan Hou",       agencies: 800, sales: 1500000, rn: 1875, tr: 1875, ht: 1875, car: 1875, vs: 15 },
              { name: "Maria Lopez",    agencies: 300, sales: 600000,  rn: 2000, tr: 2000, ht: 2000, car: 2000, vs: 10 },
              { name: "Juan Salazar",   agencies: 100, sales: 400000,  rn: 4000, tr: 4000, ht: 4000, car: 4000, vs: -5 },
              { name: "Hannah Briggs",  agencies: 220, sales: 720000,  rn: 1620, tr: 1490, ht: 1820, car: 1240, vs: 8 },
            ].map((r) => (
              <tr key={r.name}>
                <td className="bold">{r.name}</td>
                <td className="num mono">{r.agencies}</td>
                <td className="num mono">{r.sales.toLocaleString()}</td>
                <td className="num mono">{r.rn.toLocaleString()}</td>
                <td className="num mono">{r.tr.toLocaleString()}</td>
                <td className="num mono">{r.ht.toLocaleString()}</td>
                <td className="num mono">{r.car.toLocaleString()}</td>
                <td className="num mono" style={{ color: r.vs >= 0 ? "var(--success)" : "var(--danger)" }}>
                  {r.vs >= 0 ? "+" : ""}{r.vs}%
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <div style={{ height: 18 }} />

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <Card title="Sales Growth by Market & Product" sub="Comparison vs. last year" flush>
          <table className="tbl">
            <thead><tr><th>Market</th><th>Product</th><th className="num">This year</th><th className="num">Last year</th><th className="num">Growth</th></tr></thead>
            <tbody>
              <tr><td>Europe</td><td><Tag kind="hotel">Accommodation</Tag></td><td className="num mono">1,500,000</td><td className="num mono">1,304,000</td><td className="num mono" style={{ color: "var(--success)" }}>+15%</td></tr>
              <tr><td>Europe</td><td><Tag kind="transfer">Transfer</Tag></td><td className="num mono">600,000</td><td className="num mono">545,000</td><td className="num mono" style={{ color: "var(--success)" }}>+10%</td></tr>
              <tr><td>Asia</td><td><Tag kind="rental">Rental Cars</Tag></td><td className="num mono">400,000</td><td className="num mono">420,000</td><td className="num mono" style={{ color: "var(--danger)" }}>−5%</td></tr>
              <tr><td>LATAM</td><td><Tag kind="hotel">Accommodation</Tag></td><td className="num mono">325,000</td><td className="num mono">270,000</td><td className="num mono" style={{ color: "var(--success)" }}>+20%</td></tr>
              <tr><td>UK</td><td><Tag kind="flight">Flight</Tag></td><td className="num mono">186,000</td><td className="num mono">198,000</td><td className="num mono" style={{ color: "var(--danger)" }}>−6%</td></tr>
            </tbody>
          </table>
        </Card>
        <Card title="Sales by Product & City" flush>
          <table className="tbl">
            <thead><tr><th>City</th><th className="num">Accommodation</th><th className="num">Transfer</th><th className="num">Rental Cars</th><th className="num">Growth</th></tr></thead>
            <tbody>
              <tr><td>Anaheim</td><td className="num mono">€141,000</td><td className="num mono">€287,000</td><td className="num mono">€264,000</td><td className="num mono" style={{ color: "var(--success)" }}>+15%</td></tr>
              <tr><td>Las Vegas</td><td className="num mono">€725,000</td><td className="num mono">€621,000</td><td className="num mono">€82,000</td><td className="num mono" style={{ color: "var(--success)" }}>+10%</td></tr>
              <tr><td>London</td><td className="num mono">€310,000</td><td className="num mono">€351,000</td><td className="num mono">€887,000</td><td className="num mono" style={{ color: "var(--danger)" }}>−5%</td></tr>
              <tr><td>Madrid</td><td className="num mono">€520,000</td><td className="num mono">€231,000</td><td className="num mono">€140,000</td><td className="num mono" style={{ color: "var(--success)" }}>+12%</td></tr>
              <tr><td>Paris</td><td className="num mono">€612,000</td><td className="num mono">€295,000</td><td className="num mono">€170,000</td><td className="num mono" style={{ color: "var(--success)" }}>+8%</td></tr>
            </tbody>
          </table>
        </Card>
      </div>

      <div style={{ height: 18 }} />

      <Card title="Agency growth" sub={`Selected manager: ${manager}`} actions={<Segmented value="y" onChange={()=>{}} options={[{value:"m",label:"Month"},{value:"q",label:"Quarter"},{value:"y",label:"Year"}]} />}>
        <AreaChart
          height={260}
          data={[
            { label: "Jan", c: 23, p: 21 },{ label: "Feb", c: 36, p: 30 },{ label: "Mar", c: 42, p: 36 },
            { label: "Apr", c: 7, p: 17 },{ label: "May", c: 28, p: 25 },{ label: "Jun", c: 41, p: 38 },
            { label: "Jul", c: 75, p: 58 },{ label: "Aug", c: 90, p: 70 },{ label: "Sep", c: 62, p: 53 },
            { label: "Oct", c: 80, p: 64 },{ label: "Nov", c: 93, p: 72 },{ label: "Dec", c: 41, p: 36 },
          ]}
          series={[
            { key: "c", name: "Current", color: "#635bff" },
            { key: "p", name: "Previous", color: "#a78bfa" },
          ]}
        />
      </Card>

      <div style={{ height: 18 }} />

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <Card title="Agency Potential" flush>
          <table className="tbl">
            <thead><tr><th>Potential level</th><th className="num">Number of agencies</th><th className="num">Total revenue</th></tr></thead>
            <tbody>
              <tr><td><Badge tone="success">High</Badge></td><td className="num mono">142</td><td className="num mono">€1,500,000</td></tr>
              <tr><td><Badge tone="info">Normal</Badge></td><td className="num mono">86</td><td className="num mono">€600,000</td></tr>
              <tr><td><Badge tone="neutral">Low</Badge></td><td className="num mono">38</td><td className="num mono">€400,000</td></tr>
            </tbody>
          </table>
        </Card>
        <Card title="Agency Markup Levels" flush>
          <table className="tbl">
            <thead><tr><th>Markup level</th><th className="num">Number of agencies</th><th className="num">Avg. margin</th></tr></thead>
            <tbody>
              <tr><td><Badge tone="indigo">Unique</Badge></td><td className="num mono">22</td><td className="num mono">18.5%</td></tr>
              <tr><td><Badge tone="warning">Gold</Badge></td><td className="num mono">96</td><td className="num mono">14.2%</td></tr>
              <tr><td><Badge tone="neutral">Silver</Badge></td><td className="num mono">148</td><td className="num mono">9.8%</td></tr>
            </tbody>
          </table>
        </Card>
      </div>
    </div>
  );
}

function KpiProgress({ label, value, actual, target, color }) {
  return (
    <div style={{ background: "var(--bg-subtle)", padding: 16, borderRadius: 10, display: "flex", alignItems: "center", gap: 16 }}>
      <Gauge value={value} color={color} size={120} />
      <div>
        <div className="muted tiny">{label}</div>
        <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em" }}>{actual}</div>
        <div className="tiny muted">of {target} target</div>
      </div>
    </div>
  );
}

// ============================================================
// PAGE: REBOOKING TOOL
//
// Re-shops refundable bookings twice a day. When a cheaper price
// is found for the same room and conditions, the system auto-rebooks
// with the client's data and releases the savings to the agency.
// ============================================================
function PageRebooking() {
  const [watched, setWatched] = useState(null);
  const [tab, setTab] = useState("watching");

  const KPIS = [
    { id: "orig",   label: "Original Bookings",                value: "3,000",     delta: "+8.0%",  dir: "up",   spark: [22,28,26,31,34,37,42,40,48,52,55,58], color: "#635bff" },
    { id: "value",  label: "Total Value of Original Bookings", value: "€72,000",   delta: "−6.0%", dir: "down", spark: [62,60,58,55,52,48,46,44,42,40,38,36], color: "#d4366a" },
    { id: "avg",    label: "Average Savings",                  value: "12%",       delta: "+16.0%", dir: "up",   spark: [6,7,7,8,9,9,10,10,11,11,12,12],       color: "#0e7c66" },
    { id: "succ",   label: "Successful Rebookings",            value: "1,250",     delta: "+16.0%", dir: "up",   spark: [110,128,142,160,180,210,240,270,300,330,360,400], color: "#a78bfa" },
    { id: "savings",label: "Total Savings",                    value: "€72,000",   delta: "−8.0%",  dir: "down", spark: [38,40,42,44,46,48,52,50,54,56,58,60], color: "#ff9f43" },
    { id: "pct",    label: "Percentage of Rebooked",           value: "12%",       delta: "−8.0%",  dir: "down", spark: [6,7,9,10,11,12,13,12,11,12,13,12],    color: "#00d4ff" },
  ];

  const WATCHING = [
    { ref: "BK-12482", hotel: "Marriott Marbella Beach Resort",   room: "Deluxe Sea-View",  rate: "B&B · Refundable",        agency: "OptiTron Tech",       original: 940,  current: 812,  checks: 14, nextCheck: "in 4h 12m",  status: "Watching" },
    { ref: "BK-12481", hotel: "Hilton London Park Lane",          room: "Executive King",   rate: "Half Board · Refundable", agency: "Northwind Travel",    original: 1820, current: 1820, checks: 9,  nextCheck: "in 6h 02m",  status: "Watching" },
    { ref: "BK-12479", hotel: "AC Hotel Barcelona Forum",         room: "Premium Twin",     rate: "B&B · Refundable",        agency: "Wired World",         original: 612,  current: 528,  checks: 21, nextCheck: "in 2h 45m",  status: "Watching" },
    { ref: "BK-12476", hotel: "Olympia Athens Centre",            room: "Junior Suite",     rate: "Room Only · Refundable",  agency: "Pacific Horizons",    original: 480,  current: 480,  checks: 6,  nextCheck: "in 5h 14m",  status: "Watching" },
    { ref: "BK-12471", hotel: "Bavaria Hotels Munich Mitte",      room: "Standard Double",  rate: "B&B · Refundable",        agency: "Industrial Dynamics", original: 280,  current: 248,  checks: 28, nextCheck: "Locked-in",  status: "Locked" },
    { ref: "BK-12465", hotel: "Aurora Routes Oslo Fjord",         room: "Family Cottage",   rate: "Full Board · Refundable", agency: "Aurora Routes",       original: 1310, current: 1310, checks: 4,  nextCheck: "Paused",     status: "Paused" },
    { ref: "BK-12459", hotel: "Costa Cruises — Mediterranean 7n", room: "Balcony BD2",      rate: "All-Incl · Refundable",   agency: "Paramount Products",  original: 1840, current: 1640, checks: 18, nextCheck: "in 3h 26m",  status: "Watching" },
  ];

  const EVENTS = [
    { oldRef: "BK-12420", newRef: "BK-12420-R1", original: 287000, saved: 23000, pct: 8,  agency: "Justin Martinez", when: "12 min ago", hotel: "Marriott Marbella",  room: "Deluxe Sea-View · B&B" },
    { oldRef: "BK-12418", newRef: "BK-12418-R1", original: 621000, saved: 54000, pct: 8,  agency: "Ryan Young",      when: "42 min ago", hotel: "AC Hotel Barcelona", room: "Premium Twin · B&B" },
    { oldRef: "BK-12415", newRef: "BK-12415-R1", original: 351000, saved: 17500, pct: 5,  agency: "John Clark",      when: "1 hr ago",   hotel: "Hilton London",      room: "Executive King · HB" },
    { oldRef: "BK-12410", newRef: "BK-12410-R2", original: 198000, saved: 21800, pct: 11, agency: "Maria Lopez",     when: "2 hr ago",   hotel: "Costa Cruises",      room: "Balcony BD2 · AI" },
    { oldRef: "BK-12405", newRef: "BK-12405-R1", original: 412000, saved: 32900, pct: 8,  agency: "Hannah Briggs",   when: "3 hr ago",   hotel: "Bavaria Munich",     room: "Standard Double · B&B" },
    { oldRef: "BK-12399", newRef: "BK-12399-R1", original: 145000, saved: 8700,  pct: 6,  agency: "Pierre Allain",   when: "5 hr ago",   hotel: "Olympia Athens",     room: "Junior Suite · RO" },
    { oldRef: "BK-12392", newRef: "BK-12392-R3", original: 720000, saved: 91200, pct: 13, agency: "Sofia Vargas",    when: "Yesterday",  hotel: "Aurora Fjord",       room: "Family Cottage · FB" },
  ];

  const PERF = [
    { city: "Marbella",  total: 6735, savings: 287000, rebooked: 264000, growth: 15, top: "Marriott Beach Resort" },
    { city: "Tenerife",  total: 4162, savings: 621000, rebooked: 82000,  growth: 10, top: "AC Hotel Costa" },
    { city: "Lisbon",    total: 1944, savings: 351000, rebooked: 887000, growth: -5, top: "Olissippo Lapa" },
    { city: "Barcelona", total: 3210, savings: 198000, rebooked: 412000, growth: 12, top: "AC Hotel Forum" },
    { city: "Madrid",    total: 2860, savings: 412000, rebooked: 320000, growth: 9,  top: "AC Hotel Cuzco" },
    { city: "London",    total: 5128, savings: 720000, rebooked: 510000, growth: 7,  top: "Hilton Park Lane" },
  ];

  const MONTHLY = [
    { label: "Jan", saving: 24, rebookings: 22 },
    { label: "Feb", saving: 37, rebookings: 31 },
    { label: "Mar", saving: 60, rebookings: 49 },
    { label: "Apr", saving: 8,  rebookings: 12 },
    { label: "May", saving: 30, rebookings: 27 },
    { label: "Jun", saving: 41, rebookings: 38 },
    { label: "Jul", saving: 105,rebookings: 86 },
    { label: "Aug", saving: 90, rebookings: 78 },
    { label: "Sep", saving: 67, rebookings: 55 },
    { label: "Oct", saving: 88, rebookings: 71 },
    { label: "Nov", saving: 92, rebookings: 78 },
    { label: "Dec", saving: 42, rebookings: 36 },
  ];

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-head__title">Rebooking Tool</h1>
          <div className="page-head__sub">
            Re-shop refundable bookings twice a day. When a cheaper price is found for the same room and conditions, the system auto-rebooks with the client's data and releases the savings.
          </div>
        </div>
        <div className="page-head__actions">
          <Button kind="secondary" icon={<Icon.Refresh />}>Run check now</Button>
          <Button kind="primary" icon={<Icon.Plus />}>Watch a booking</Button>
        </div>
      </div>

      <div className="filter-bar" style={{ borderRadius: 8, border: "1px solid var(--border)", marginBottom: 18 }}>
        <Field label="Market"><select className="select" style={{ minWidth: 140 }}><option>All markets</option><option>Iberia</option><option>DACH</option><option>UK</option><option>Nordics</option></select></Field>
        <Field label="Agency"><select className="select" style={{ minWidth: 180 }}><option>All agencies</option>{window.MOCK.TRAVEL_AGENCIES.map((a) => <option key={a.id}>{a.name}</option>)}</select></Field>
        <Field label="Vendor / Hotel"><select className="select" style={{ minWidth: 180 }}><option>All vendors</option>{window.MOCK.VENDORS.map((v) => <option key={v.id}>{v.name}</option>)}</select></Field>
        <Field label="Period"><select className="select" style={{ minWidth: 130 }}><option>Today</option><option>Last 7 days</option><option>Last 30 days</option><option>YTD</option></select></Field>
        <span className="spacer" />
        <Button kind="secondary" icon={<Icon.Download />}>Export</Button>
      </div>

      <div className="grid grid--3" style={{ gap: 14, marginBottom: 14 }}>
        {KPIS.slice(0, 3).map((k) => <RebookingKpi key={k.id} k={k} />)}
      </div>
      <div className="grid grid--3" style={{ gap: 14, marginBottom: 18 }}>
        {KPIS.slice(3).map((k) => <RebookingKpi key={k.id} k={k} />)}
      </div>

      <div className="grid grid--2" style={{ gap: 14, marginBottom: 18 }}>
        <Card title="Monthly Saving" sub="Compared to previous period"
          actions={<Segmented value="y" onChange={() => {}} options={[{value:"m",label:"Month"},{value:"q",label:"Quarter"},{value:"y",label:"Year"}]} />}>
          <AreaChart
            height={220}
            data={MONTHLY.map((m) => ({ label: m.label, current: m.saving, previous: Math.round(m.saving * 0.85) }))}
            valueFmt={(v) => "€" + v + "k"}
            series={[
              { key: "current",  name: "This year", color: "#00d4ff" },
              { key: "previous", name: "Last year", color: "#a78bfa" },
            ]}
          />
        </Card>
        <Card title="Rebookings" sub="Successful rebooking events"
          actions={<Segmented value="y" onChange={() => {}} options={[{value:"m",label:"Month"},{value:"q",label:"Quarter"},{value:"y",label:"Year"}]} />}>
          <AreaChart
            height={220}
            data={MONTHLY.map((m) => ({ label: m.label, current: m.rebookings, previous: Math.round(m.rebookings * 0.82) }))}
            series={[
              { key: "current",  name: "This year", color: "#635bff" },
              { key: "previous", name: "Last year", color: "#a78bfa" },
            ]}
          />
        </Card>
      </div>

      <Tabs
        active={tab}
        onChange={setTab}
        tabs={[
          { id: "watching",   label: "Currently watching", count: WATCHING.length },
          { id: "events",     label: "Recent rebookings",  count: EVENTS.length },
          { id: "performance",label: "Performance by destination" },
          { id: "settings",   label: "Rebooking settings" },
        ]}
      />

      {tab === "watching"    && <WatchingTable rows={WATCHING} onOpen={setWatched} />}
      {tab === "events"      && <EventsTable rows={EVENTS} />}
      {tab === "performance" && <PerfTable rows={PERF} />}
      {tab === "settings"    && <RebookingSettings />}

      <WatchedBookingDrawer watched={watched} onClose={() => setWatched(null)} />
    </div>
  );
}

function RebookingKpi({ k }) {
  return (
    <div className="metric" style={{ display: "flex", flexDirection: "column", gap: 6, position: "relative", overflow: "hidden" }}>
      <div className="metric__label" style={{ display: "flex", justifyContent: "space-between" }}>
        <span>{k.label}</span>
        <span className={`metric__delta metric__delta--${k.dir}`}>
          {k.dir === "down" ? <Icon.ArrowDown size={12} /> : <Icon.ArrowUp size={12} />}{k.delta}
        </span>
      </div>
      <div className="row" style={{ alignItems: "flex-end", justifyContent: "space-between" }}>
        <div className="metric__value">{k.value}</div>
        <Sparkline values={k.spark} color={k.color} width={120} height={36} />
      </div>
    </div>
  );
}

function WatchingTable({ rows, onOpen }) {
  return (
    <div>
      <div className="filter-bar">
        <input className="input input--search" placeholder="Search by booking ref, hotel or agency…" style={{ width: 320 }} />
        <select className="select"><option>All statuses</option><option>Watching</option><option>Locked</option><option>Paused</option><option>Rebooked</option></select>
        <select className="select"><option>Any savings</option><option>≥ 5%</option><option>≥ 10%</option><option>≥ 20%</option></select>
        <span className="spacer" />
        <span className="tiny muted row" style={{ gap: 6 }}>
          <Icon.Clock size={12} /> Last system check 11 min ago · next 4 h 12 min
        </span>
      </div>
      <div className="tbl-wrap tbl-wrap--linked">
        <table className="tbl">
          <thead>
            <tr>
              <th>Booking</th>
              <th>Hotel / Room · Rate plan</th>
              <th>Agency</th>
              <th className="num">Original</th>
              <th className="num">Current best</th>
              <th className="num">Δ Saving</th>
              <th className="num">Checks</th>
              <th>Next check</th>
              <th>Status</th>
              <th className="col-actions"></th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r) => {
              const delta = r.original - r.current;
              const pct = Math.round((delta / r.original) * 100);
              return (
                <tr key={r.ref}>
                  <td className="mono"><a href="#" onClick={(e) => { e.preventDefault(); onOpen(r); }}>{r.ref}</a></td>
                  <td>
                    <div className="bold">{r.hotel}</div>
                    <div className="tiny muted">{r.room} · {r.rate}</div>
                  </td>
                  <td>{r.agency}</td>
                  <td className="num mono">€{r.original.toLocaleString()}</td>
                  <td className="num mono bold" style={{ color: delta > 0 ? "var(--success)" : "var(--ink-1)" }}>€{r.current.toLocaleString()}</td>
                  <td className="num mono">
                    {delta > 0
                      ? <span style={{ color: "var(--success)" }}>−€{delta.toLocaleString()} <span className="tiny">({pct}%)</span></span>
                      : <span className="muted">— no drop</span>}
                  </td>
                  <td className="num mono">{r.checks}</td>
                  <td className="mono muted">{r.nextCheck}</td>
                  <td>
                    {r.status === "Watching" && <Badge tone="info">Watching</Badge>}
                    {r.status === "Locked"   && <Badge tone="success">Locked-in</Badge>}
                    {r.status === "Paused"   && <Badge tone="warning">Paused</Badge>}
                    {r.status === "Rebooked" && <Badge tone="success">Rebooked</Badge>}
                  </td>
                  <td className="col-actions">
                    <div className="row" style={{ gap: 4, justifyContent: "flex-end" }}>
                      <Button kind="ghost" size="sm" icon={<Icon.Refresh />} iconOnly title="Force re-check" />
                      <Button kind="secondary" size="sm" onClick={() => onOpen(r)}>View</Button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <Pager page={1} pageSize={10} total={rows.length} onPage={() => {}} />
    </div>
  );
}

function EventsTable({ rows }) {
  return (
    <div>
      <div className="filter-bar">
        <input className="input input--search" placeholder="Search by old / new ref, agency or hotel…" style={{ width: 340 }} />
        <select className="select"><option>Any saving %</option><option>≥ 5%</option><option>≥ 10%</option><option>≥ 15%</option></select>
        <span className="spacer" />
        <Button kind="secondary" icon={<Icon.Download />}>Export</Button>
      </div>
      <div className="tbl-wrap tbl-wrap--linked">
        <table className="tbl">
          <thead>
            <tr>
              <th>When</th>
              <th>Old Booking Ref</th>
              <th>New Booking Ref</th>
              <th>Hotel / Room</th>
              <th className="num">Original Amount</th>
              <th className="num">Amount Saved</th>
              <th className="num">% saved</th>
              <th>Agency name</th>
              <th className="col-actions"></th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r) => (
              <tr key={r.oldRef}>
                <td className="mono muted">{r.when}</td>
                <td className="mono">{r.oldRef}</td>
                <td className="mono"><span style={{ color: "var(--indigo)" }}>{r.newRef}</span></td>
                <td>
                  <div className="bold">{r.hotel}</div>
                  <div className="tiny muted">{r.room}</div>
                </td>
                <td className="num mono">€{r.original.toLocaleString()}</td>
                <td className="num mono bold" style={{ color: "var(--success)" }}>−€{r.saved.toLocaleString()}</td>
                <td className="num mono"><Badge tone={r.pct >= 10 ? "success" : "info"}>{r.pct}%</Badge></td>
                <td>{r.agency}</td>
                <td className="col-actions">
                  <Button kind="secondary" size="sm">View</Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <Pager page={1} pageSize={10} total={rows.length} onPage={() => {}} />
    </div>
  );
}

function PerfTable({ rows }) {
  return (
    <div className="tbl-wrap tbl-wrap--linked" style={{ borderTop: "1px solid var(--border)", borderRadius: 8 }}>
      <table className="tbl">
        <thead>
          <tr>
            <th>City</th>
            <th className="num">Total bookings monitored</th>
            <th className="num">Total Savings</th>
            <th className="num">Rebooked value</th>
            <th className="num">Growth</th>
            <th>Top hotel</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr key={r.city}>
              <td className="bold">{r.city}</td>
              <td className="num mono">{r.total.toLocaleString()}</td>
              <td className="num mono">€{r.savings.toLocaleString()}</td>
              <td className="num mono">€{r.rebooked.toLocaleString()}</td>
              <td className="num mono" style={{ color: r.growth >= 0 ? "var(--success)" : "var(--danger)" }}>
                {r.growth >= 0 ? "+" : ""}{r.growth}%
              </td>
              <td className="muted">{r.top}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function RebookingSettings() {
  return (
    <div className="grid grid--2" style={{ gap: 18 }}>
      <Card title="Rebooking rules">
        <Field label="Minimum savings threshold (%)" hint="The system will only rebook when the saving is greater than this.">
          <div className="row" style={{ gap: 8 }}>
            <input className="input" type="number" defaultValue="5" style={{ width: 100 }} />
            <span className="muted">%</span>
          </div>
        </Field>
        <div style={{ height: 14 }} />
        <Field label="Re-check frequency" hint="How often to query the vendor for a fresh quote.">
          <select className="select" defaultValue="twice">
            <option value="hourly">Every hour</option>
            <option value="6h">Every 6 hours</option>
            <option value="twice">Twice a day (recommended)</option>
            <option value="daily">Once a day</option>
          </select>
        </Field>
        <div style={{ height: 14 }} />
        <Field label="Stop watching when" hint="Conditions to take a booking off the watchlist.">
          <div className="col" style={{ gap: 8 }}>
            <label className="row" style={{ gap: 8 }}><input type="checkbox" className="checkbox" defaultChecked /> Less than 48 h before check-in</label>
            <label className="row" style={{ gap: 8 }}><input type="checkbox" className="checkbox" defaultChecked /> Rate plan turned non-refundable</label>
            <label className="row" style={{ gap: 8 }}><input type="checkbox" className="checkbox" /> A successful rebook already happened</label>
            <label className="row" style={{ gap: 8 }}><input type="checkbox" className="checkbox" /> Vendor opted out of rebooking</label>
          </div>
        </Field>
        <div style={{ height: 14 }} />
        <Field label="Maximum rebooks per booking">
          <select className="select" defaultValue="2">
            <option>1</option><option>2</option><option>3</option><option>Unlimited</option>
          </select>
        </Field>
      </Card>

      <Card title="Approval & penalties">
        <Field label="Handle rebooking requests with penalties">
          <select className="select" defaultValue="auto">
            <option value="auto">Auto-Approve (if saving &gt; penalty)</option>
            <option value="ask">Ask the agency to confirm</option>
            <option value="never">Never accept a penalty</option>
          </select>
        </Field>
        <div style={{ height: 14 }} />
        <div className="row" style={{ justifyContent: "space-between", padding: "8px 0" }}>
          <div>
            <div className="bold">Notify agency on successful rebook</div>
            <div className="tiny muted">Sends an email summary with old + new prices.</div>
          </div>
          <Toggle on onChange={() => {}} />
        </div>
        <div className="divider" />
        <div className="row" style={{ justifyContent: "space-between", padding: "8px 0" }}>
          <div>
            <div className="bold">Notify client on successful rebook</div>
            <div className="tiny muted">Plain confirmation, no price changes shown.</div>
          </div>
          <Toggle on onChange={() => {}} />
        </div>
        <div className="divider" />
        <div className="row" style={{ justifyContent: "space-between", padding: "8px 0" }}>
          <div>
            <div className="bold">Pause tool globally</div>
            <div className="tiny muted">Stops every re-check. Existing bookings stay locked-in.</div>
          </div>
          <Toggle on={false} onChange={() => {}} />
        </div>
      </Card>

      <div style={{ gridColumn: "1 / -1" }}>
        <Card title="Eligible vendors & rate plans" sub="Which suppliers allow re-shopping under the same rate"
          actions={<Button kind="secondary" size="sm" icon={<Icon.Plus />}>Add vendor</Button>}
          flush>
          <table className="tbl">
            <thead><tr><th>Vendor</th><th>Rate plans allowed</th><th className="num">Refundable share</th><th className="num">Avg saving</th><th>Status</th><th className="col-actions"></th></tr></thead>
            <tbody>
              <tr><td className="bold">Marriott International</td><td>Best Available, Member, Corporate</td><td className="num mono">68%</td><td className="num mono" style={{ color: "var(--success)" }}>9.2%</td><td><Badge tone="success">Enabled</Badge></td><td className="col-actions"><Button kind="ghost" size="sm" iconOnly icon={<Icon.Edit />} /></td></tr>
              <tr><td className="bold">Hilton Worldwide</td><td>Flexible, Honors, Senior</td><td className="num mono">71%</td><td className="num mono" style={{ color: "var(--success)" }}>7.8%</td><td><Badge tone="success">Enabled</Badge></td><td className="col-actions"><Button kind="ghost" size="sm" iconOnly icon={<Icon.Edit />} /></td></tr>
              <tr><td className="bold">AC Hotels Group</td><td>BAR, Corporate</td><td className="num mono">54%</td><td className="num mono" style={{ color: "var(--success)" }}>11.4%</td><td><Badge tone="success">Enabled</Badge></td><td className="col-actions"><Button kind="ghost" size="sm" iconOnly icon={<Icon.Edit />} /></td></tr>
              <tr><td className="bold">Costa Cruises</td><td>Flexible, Family</td><td className="num mono">42%</td><td className="num mono" style={{ color: "var(--success)" }}>13.2%</td><td><Badge tone="success">Enabled</Badge></td><td className="col-actions"><Button kind="ghost" size="sm" iconOnly icon={<Icon.Edit />} /></td></tr>
              <tr><td className="bold">Bavaria Hotels GmbH</td><td>BAR</td><td className="num mono">28%</td><td className="num mono muted">—</td><td><Badge tone="warning">Restricted</Badge></td><td className="col-actions"><Button kind="ghost" size="sm" iconOnly icon={<Icon.Edit />} /></td></tr>
              <tr><td className="bold">Olympia Tours</td><td>—</td><td className="num mono">0%</td><td className="num mono muted">—</td><td><Badge tone="neutral">Disabled</Badge></td><td className="col-actions"><Button kind="ghost" size="sm" iconOnly icon={<Icon.Edit />} /></td></tr>
            </tbody>
          </table>
        </Card>
      </div>
    </div>
  );
}

function WatchedBookingDrawer({ watched, onClose }) {
  if (!watched) return null;
  const w = watched;
  const delta = w.original - w.current;
  const pct = ((delta / w.original) * 100).toFixed(1);
  const history = [];
  let p = w.original;
  for (let i = 12; i >= 0; i--) {
    p = Math.max(w.current, p - 6 - (i % 4));
    if (i % 3 === 0) p += 4;
    history.push(Math.round(p));
  }
  history.push(w.current);

  return (
    <>
      <div className="drawer-veil" onClick={onClose} />
      <div className="drawer">
        <div className="modal__head">
          <div>
            <div className="row" style={{ gap: 8 }}>
              <h3 className="modal__title">Watched booking · <span className="mono">{w.ref}</span></h3>
              {w.status === "Watching" && <Badge tone="info">Watching</Badge>}
              {w.status === "Locked"   && <Badge tone="success">Locked-in</Badge>}
              {w.status === "Paused"   && <Badge tone="warning">Paused</Badge>}
            </div>
            <div className="muted tiny" style={{ marginTop: 2 }}>{w.hotel} — {w.room} · {w.rate}</div>
          </div>
          <button className="modal__close" onClick={onClose}><Icon.X /></button>
        </div>
        <div className="modal__body">
          <div className="grid grid--3" style={{ gap: 12, marginBottom: 16 }}>
            <Metric label="Original price" value={`€${w.original.toLocaleString()}`} hint="Booked rate" />
            <Metric label="Current best" value={`€${w.current.toLocaleString()}`} hint={`Last check ${w.checks * 12}m ago`} accent />
            <Metric label="Potential saving"
              value={delta > 0 ? `€${delta.toLocaleString()}` : "—"}
              delta={delta > 0 ? `${pct}%` : null}
              deltaDir="up"
              hint="Same room · same conditions"
            />
          </div>

          <Card title="Price history" sub={`Re-shopped ${w.checks} times since booking`}>
            <AreaChart
              height={180}
              data={history.map((v, i) => ({ label: `T-${history.length - 1 - i}`, p: v }))}
              valueFmt={(v) => "€" + v}
              series={[{ key: "p", name: "Vendor quote", color: "#635bff" }]}
            />
          </Card>

          <div style={{ height: 14 }} />
          <Card title="Booking details">
            <dl className="dl">
              <dt>Booking ref</dt><dd className="mono">{w.ref}</dd>
              <dt>Agency</dt><dd>{w.agency}</dd>
              <dt>Hotel</dt><dd>{w.hotel}</dd>
              <dt>Room</dt><dd>{w.room}</dd>
              <dt>Rate plan</dt><dd>{w.rate}</dd>
              <dt>Check-in</dt><dd className="mono">Jul 14, 2026 · 14:00</dd>
              <dt>Check-out</dt><dd className="mono">Jul 19, 2026 · 11:00</dd>
              <dt>Lead pax</dt><dd>D. García (DNI 42178890K)</dd>
              <dt>Free cancellation until</dt><dd className="mono">Jul 9, 2026 · 23:59</dd>
              <dt>Next system check</dt><dd className="mono">{w.nextCheck}</dd>
            </dl>
          </Card>

          <div style={{ height: 14 }} />
          <Card title="Activity">
            <ul style={{ margin: 0, padding: 0, listStyle: "none", fontSize: 13 }}>
              <li className="row" style={{ gap: 10, padding: "8px 0", borderBottom: "1px solid var(--border-hairline)" }}>
                <Icon.Refresh stroke="var(--indigo)" /><div><b>Auto re-check</b> · vendor quote €{w.current} <span className="tiny muted">— 11 min ago</span></div>
              </li>
              <li className="row" style={{ gap: 10, padding: "8px 0", borderBottom: "1px solid var(--border-hairline)" }}>
                <Icon.Refresh stroke="var(--indigo)" /><div><b>Auto re-check</b> · vendor quote €{w.current + 12} <span className="tiny muted">— 12 h ago</span></div>
              </li>
              <li className="row" style={{ gap: 10, padding: "8px 0", borderBottom: "1px solid var(--border-hairline)" }}>
                <Icon.Check stroke="var(--success)" /><div><b>Watch started</b> by Maria Lopez <span className="tiny muted">— 7 days ago</span></div>
              </li>
              <li className="row" style={{ gap: 10, padding: "8px 0" }}>
                <Icon.Bookings stroke="var(--ink-3)" /><div><b>Original booking created</b> via Agency portal <span className="tiny muted">— 8 days ago</span></div>
              </li>
            </ul>
          </Card>
        </div>
        <div className="modal__foot">
          <Button kind="ghost">Pause watch</Button>
          <span className="spacer" />
          <Button kind="secondary" icon={<Icon.Refresh />}>Re-check now</Button>
          {delta > 0
            ? <Button kind="primary" icon={<Icon.Check />}>Rebook for €{w.current.toLocaleString()} — save €{delta.toLocaleString()}</Button>
            : <Button kind="primary" disabled>No saving yet</Button>}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { PageDashboard, PageSales, PageRebooking });
