// towing.jsx — Towing checklist (A320/A330, before/after) + aerodrome ground
// movement charts (DMK), from the Engineering Safety Towing Checklist Rev.1.
// Exported to window.
const { useState: useTw } = React;

const TOW = {
  hyd: { A320: "Y", A330: "B" },
  groups: [
    { key: "before", label: "Before Towing", items: [
      "LDG & BYPASS PINS — INSTALLED",
      "MCDU INIT — FLT NBR · A/C REGISTER · FROM BAY → TO BAY",
      "ALL DOORS — CLOSED",
      "PAX STEP — REMOVED",
      "{H} HYD PRESSURIZATION — CHECKED · BRAKE ACCUM 3000 PSI",
      "NAV & LOGO LIGHTS — ON",
      "BEACON LIGHT — ON",
      "VHF 1 COMM — SET",
      "TRANSPONDER — CODE 2000 ON",
      "FLIGHT INTERPHONE — SET",
      "CHOCKS — REMOVED",
      "PARKING BRAKE — RELEASED",
    ] },
    { key: "after", label: "After Towing", items: [
      "CHOCKS — INSTALLED",
      "NAV & LOGO LIGHTS — OFF",
      "BEACON LIGHT — OFF",
      "VHF 1 COMM — OFF",
      "FLIGHT INTERPHONE — OFF",
      "TRANSPONDER — CODE 2000 OFF",
      "{H} HYD PRESSURIZATION — OFF",
      "PARKING BRAKE — RELEASED",
      "LDG PINS — REMOVED BEFORE FLIGHT",
    ] },
  ],
};
const CHARTS = Array.from({ length: 13 }, (_, i) => `assets/ground-chart/chart-${String(i + 1).padStart(2, "0")}.jpg`);

// Ground control frequencies by apron zone (DMK) — set VHF 1 to match the zone you tow in.
const GND_FREQ = [
  { zone: "GND NORTH", freq: "122.5", area: "North Apron" },
  { zone: "GND SOUTH", freq: "121.9", area: "South · Cargo" },
  { zone: "GND EAST", freq: "121.9", area: "East Apron" },
  { zone: "TWR", freq: "118.1", area: "Tower (DMK)" },
];

function TowingScreen({ onBack, onSave }) {
  const [type, setType] = useTw("A320");
  const [done, setDone] = useTw({});
  const [chart, setChart] = useTw(false);
  const [zoom, setZoom] = useTw(null);
  const h = TOW.hyd[type];
  const total = TOW.groups.reduce((s, g) => s + g.items.length, 0);
  const doneN = Object.keys(done).filter((k) => done[k]).length;
  const toggle = (k) => setDone((d) => ({ ...d, [k]: !d[k] }));
  const reset = () => setDone({});
  const save = () => onSave({ type, done: doneN, total });

  return (
    <>
    <div className="screen-scroll tow">
      <TopBar title="Towing Checklist" sub="Before & after towing (A320/A330)" onBack={onBack}
        right={<span className="apipill"><i className="apipill-dot" />{doneN}/{total}</span>} />

      <div className="fuel-type">
        {["A320", "A330"].map((tp) => (
          <button key={tp} className={"typebtn" + (type === tp ? " typebtn--on" : "")} onClick={() => setType(tp)}>
            <b>{tp}</b><span>{TOW.hyd[tp]} HYD system</span>
          </button>
        ))}
      </div>

      <div className="tow-body">
        <button className="tow-chartbtn" onClick={() => setChart(true)}>
          <Ic.pin width="17" height="17" /><span>Aerodrome Ground Movement Chart · DMK</span>
          <b className="mono">{CHARTS.length}</b><Ic.chevron width="16" height="16" />
        </button>

        <div className="gnd-card">
          <div className="gnd-head">Ground frequencies · DMK <span>set VHF 1 by towing zone</span></div>
          <div className="gnd-list">
            {GND_FREQ.map((g) => (
              <div key={g.zone} className={"gnd-row" + (g.zone === "TWR" ? " gnd-row--twr" : "")}>
                <div className="gnd-zone"><b>{g.zone}</b><span>{g.area}</span></div>
                <div className="gnd-freq mono">{g.freq}<i>MHz</i></div>
              </div>
            ))}
          </div>
        </div>

        {TOW.groups.map((g) => {
          const gd = g.items.filter((_, i) => done[g.key + i]).length;
          return (
            <div key={g.key} className="tow-group">
              <div className="tow-group-h"><span>{g.label}</span><span className="tow-grp-n mono">{gd}/{g.items.length}</span></div>
              {g.items.map((s, i) => {
                const k = g.key + i; const on = !!done[k];
                return (
                  <button key={k} className={"tow-item" + (on ? " tow-item--on" : "")} onClick={() => toggle(k)}>
                    <span className="tow-check">{on && <Ic.check width="15" height="15" />}</span>
                    <span className="tow-text">{s.replace("{H}", h)}</span>
                  </button>
                );
              })}
            </div>
          );
        })}

        <div className="tow-note"><Ic.warn width="15" height="15" /><span>REF. AMM and EPM Vol.2 for the towing procedure · FOR MAINTENANCE ONLY</span></div>
        {doneN > 0 && <button className="tow-reset" onClick={reset}>Clear all checks</button>}
      </div>
      <div className="scroll-pad" />
    </div>

    <div className="savebar">
      <Btn kind="ghost" onClick={onBack}>Close</Btn>
      <Btn kind="primary" full onClick={save} icon={<Ic.check width="18" height="18" />}>Save to Work Log{doneN ? ` (${doneN}/${total})` : ""}</Btn>
    </div>

    <Sheet open={chart} onClose={() => setChart(false)} title="Ground Movement Chart · DMK" full>
      <p className="sheet-lead">Ground movement chart (Don Mueang) · tap a chart to enlarge</p>
      <div className="chart-grid">
        {CHARTS.map((src, i) => (
          <button key={i} className="chart-thumb" onClick={() => setZoom(i)}>
            <img src={src} alt={"chart " + (i + 1)} loading="lazy" />
            <span className="chart-n mono">{i + 1}</span>
          </button>
        ))}
      </div>
    </Sheet>

    {zoom != null && (
      <div className="chart-zoom" onClick={() => setZoom(null)}>
        <div className="chart-zoom-scroll" onClick={(e) => e.stopPropagation()}>
          <img src={CHARTS[zoom]} alt={"chart " + (zoom + 1)} />
        </div>
        <button className="chart-zoom-x" onClick={() => setZoom(null)}><Ic.close width="20" height="20" /></button>
        <div className="chart-zoom-n mono">{zoom + 1} / {CHARTS.length} · tap outside to close · scroll to view detail</div>
      </div>
    )}
    </>
  );
}

Object.assign(window, { TowingScreen });
