// ---------------------------------------------------------------------------
// automation/TriggerPicker.tsx — WAVE 25 item 5b (contract C2, ruling R9/R14):
// ONE picker, TWO presentations.
//
// The owner's complaint (reference/ERROR 3.png) is precise: Properties →
// Trigger details → Trigger type is a native `<select>` listing all eleven
// triggers flat, with NO ICONS — beside a "+ Add trigger" menu, four inches
// away, that draws every one of them with a mark. Two controls choosing the
// same thing, looking like different features.
//
// So there is one component now. `variant="menu"` is the big flyout the empty
// state opens; `variant="field"` is the compact control in Properties, which
// shows the current choice and opens the SAME list. Category first — Time /
// Database / Connector — then the trigger, with connector rows nested under
// their product name (Gmail / Webhooks / Scraper / TikTok).
//
// ⛔ NO CLIENT UNION OVER A SERVER VOCABULARY, the builder's law and this file's
// too. The groups, their captions, their order, the connector nests and every
// description ride `TriggerOption`. What this file owns is pixels.
//
// ⛔ AND THE SELECTED STATE IS THE POINT. A `<select>` missing its `value`
// renders the FIRST option; a custom listbox renders NOTHING selected and lets
// the next patch write the blank over a real stored key. `selectedTrigger`
// (steps.ts, executed by `verify_steps.py`) owns that answer so it is asserted
// rather than eyeballed — the grouping and the selection are the two things a
// screenshot proves worst.
// ---------------------------------------------------------------------------
import { useEffect, useRef, useState } from "react";

import { brandForConnector, brandForKind, hasBrandKind } from "../connectors/brandMarks";

import type { TriggerOption } from "./automationApi";
import { groupTriggers, selectedTrigger } from "./steps";

/**
 * A trigger's icon, PER KIND. Drawn, never an emoji (owner constant).
 *
 * ⚠ MOVED HERE FROM `AutomationBuilder.tsx` (wave 25), unchanged apart from the two new keys.
 * It belongs with the picker that shows it: it was private to the builder while the ONLY marked
 * surface was the builder's own menu, and the whole of item 5b is that the compact control has
 * to wear the same marks. A second copy over there was the alternative, which is how two
 * controls choosing one thing come to look like two features in the first place.
 *
 * ⚠ THE FIRST VERSION DREW ONE GLYPH FOR ALL ELEVEN, and reading the suggested list settled it:
 * six identical arrows down the left edge is decoration, not information — the eye learns
 * nothing and the column just gets wider. Unknown keys keep the neutral arrow, so a trigger the
 * engine adds tomorrow renders plainly rather than not at all (the silent-drop rule, applied to
 * icons).
 */
export function TriggerMark({ kind = "" }: { kind?: string }) {
  /*
    ⭐⭐ WAVE 30 · ITEM 7 / R3 + R4 — A BRAND WINS OVER THE HOUSE GLYPH, and it is resolved HERE
    rather than at the four call sites. `TriggerMark` is drawn in the flyout, in the compact
    Properties control, and by `AutomationBuilder` on the trigger card; a per-call-site check is
    three chances to give the same trigger two identities on one screen.
    ⛔ The geometric glyphs BELOW ARE NOT DELETED. They are the fallback for every unbranded
    trigger and, for the two branded ones, the record of what this picker drew before the owner
    asked for logos — a magnifier with a person in it, and the same frame with a note. Deleting
    them would also delete the only description of why those two shapes differed.
  */
  const brand = brandForKind(kind);
  if (brand) return brand;
  const common = {
    width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
    strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
    "aria-hidden": true,
  };
  if (kind === "schedule")
    return (
      <svg {...common}>
        <circle cx="8" cy="8" r="5.6" />
        <path d="M8 5.2V8l2 1.4" />
      </svg>
    );
  if (kind === "event_field")
    return (
      <svg {...common}>
        <path d="M2.8 3.4h10.4l-4 4.6v4.2l-2.4 1.2V8z" />
      </svg>
    );
  if (kind === "record_created")
    return (
      <svg {...common}>
        <rect x="3" y="2.6" width="10" height="10.8" rx="1.8" />
        <path d="M8 5.8v4.4M5.8 8h4.4" />
      </svg>
    );
  if (kind === "record_updated")
    return (
      <svg {...common}>
        <rect x="3" y="2.6" width="10" height="10.8" rx="1.8" />
        <path d="M5.8 6.4h4.4M5.8 9.2h2.6" />
      </svg>
    );
  if (kind === "enters_view")
    return (
      <svg {...common}>
        <path d="M1.8 8s2.4-4 6.2-4 6.2 4 6.2 4-2.4 4-6.2 4-6.2-4-6.2-4z" />
        <circle cx="8" cy="8" r="1.7" />
      </svg>
    );
  if (kind === "webhook")
    return (
      <svg {...common}>
        <path d="M6.6 9.4 4.9 11a2.6 2.6 0 1 1-1.5-4.4" />
        <path d="M9.4 6.6 11.1 5a2.6 2.6 0 1 1 1.5 4.4" />
        <path d="M6.2 8h3.6" />
      </svg>
    );
  if (kind === "email")
    return (
      <svg {...common}>
        <rect x="2.2" y="3.6" width="11.6" height="8.8" rx="1.6" />
        <path d="m2.6 4.6 5.4 3.8 5.4-3.8" />
      </svg>
    );
  if (kind === "form_submitted")
    return (
      <svg {...common}>
        <rect x="3" y="2.6" width="10" height="10.8" rx="1.8" />
        <path d="M5.8 6h4.4M5.8 8.6h2.2M9 11l1.2 1.2L12.6 9.8" />
      </svg>
    );
  if (kind === "button_clicked")
    return (
      <svg {...common}>
        <path d="M6 3.2v6.2l1.6-1.4 1.4 3 1.6-.8-1.4-2.8 2.2-.2z" />
      </svg>
    );
  if (kind === "comment_added")
    return (
      <svg {...common}>
        <path d="M13.4 9.4a1.6 1.6 0 0 1-1.6 1.6H5.4L2.6 13.4V4.2a1.6 1.6 0 0 1 1.6-1.6h7.6a1.6 1.6 0 0 1 1.6 1.6z" />
      </svg>
    );
  /*
    WAVE 24 — a magnifier with a PERSON inside it: this one does not watch a database, it
    searches a corpus of profiles and makes rows out of what fits.
    ⚠ Deliberately not the bare magnifier — `ActionMark`'s `find_records` already owns that shape
    for "search a database", and two searches drawn identically would be the six-identical-arrows
    problem this component's header talks itself out of.
  */
  if (kind === "ig_profile_match")
    return (
      <svg {...common}>
        <circle cx="7" cy="7" r="4.4" />
        <path d="m10.4 10.4 3.2 3.2" />
        <circle cx="7" cy="5.9" r="1.3" />
        <path d="M4.9 9.7c.4-1.1 1.2-1.7 2.1-1.7s1.7.6 2.1 1.7" />
      </svg>
    );
  /*
    ⭐ WAVE 25 (R9) — THE TWO NEW PLANNED KEYS. They render FADED and `clean_trigger` refuses
    them at the door, but they still need a mark: an unmarked row in a marked list reads as a
    rendering fault rather than as "not built yet", and the neutral arrow is what every unknown
    key already gets — so the faded row would have been indistinguishable from a trigger this
    client has never heard of.
  */
  // A PAGE with a delta on it: the thing being watched is a document, and what fires is that it
  // is DIFFERENT from last time. Not the magnifier — this one watches one page rather than
  // searching a corpus, which is the distinction the Scraper nest otherwise loses.
  if (kind === "web_page_changed")
    return (
      <svg {...common}>
        <path d="M9 2.6H4.4a1.4 1.4 0 0 0-1.4 1.4v8a1.4 1.4 0 0 0 1.4 1.4h7.2a1.4 1.4 0 0 0 1.4-1.4V6.6z" />
        <path d="M9 2.6v4h4" />
        <path d="M5.6 9.4h4.2M5.6 11.4h2.4" />
      </svg>
    );
  // A MUSICAL NOTE inside the same search frame as `ig_profile_match`: same act (search a corpus
  // of profiles), different corpus. Drawing it as a second person-in-a-magnifier would say the two
  // are interchangeable, and they are not — the two networks have different schemas and, per wave
  // 29's R2, different `ut_*` families behind them.
  // ⚠ WAVE 29: this row is LIVE now (D-9 closed the trigger half). Nothing in this file changed to
  // make it so — `planned` rides the wire, which is the property that makes a server vocabulary
  // worth having. The sentence that used to end this note ("the claim D-9 is still open about")
  // was true when it was written and would have quietly aged into a lie.
  if (kind === "tiktok_profile_match")
    return (
      <svg {...common}>
        <circle cx="7" cy="7" r="4.4" />
        <path d="m10.4 10.4 3.2 3.2" />
        <path d="M8.4 4.6v3.8a1.3 1.3 0 1 1-1.3-1.3" />
        <path d="M8.4 5.6c.3.5.8.8 1.4.8" />
      </svg>
    );
  return (
    <svg {...common}>
      <path d="M3 3v6.2a2 2 0 0 0 2 2h7.4" />
      <path d="M10.2 9.2 12.8 11.2 10.2 13.2" />
    </svg>
  );
}

/**
 * The state word a row wears, or `""`.
 *
 * TWO STATES, NOT ONE, and the difference is what the reader can DO: a PLANNED trigger is
 * waiting on us, a not-ready one is waiting on a connection THEY can make. Both render; only
 * the second offers an action (the Connect button, in Properties).
 */
function rowNote(t: TriggerOption): string {
  if (t.planned) return "Coming soon";
  if (t.ready === false) return "Needs setting up";
  return "";
}

/**
 * The rows themselves, shared by both presentations — which is what makes them ONE control
 * rather than two that agree today.
 */
function TriggerList({
  options,
  value,
  disabled,
  onPick,
}: {
  options: TriggerOption[];
  value: string;
  disabled: boolean;
  onPick: (key: string) => void;
}) {
  const row = (t: TriggerOption) => {
    const on = t.key === value;
    return (
      <button
        key={t.key}
        type="button"
        role="option"
        aria-selected={on}
        // ⛔ `is-planned` ONLY FOR PLANNED, and this was wrong in the first draft. That class
        // carries `cursor: default` — it exists to say "this row is not pickable" — and a
        // not-ready trigger IS pickable (`clean_trigger` accepts it; readiness is a deployment
        // fact, not a validity one). Fading both would have put a default cursor on a live
        // control, which reads as broken rather than as unavailable. The old picker made the
        // same distinction; the two states are worded apart in `rowNote` instead.
        className={
          "autox-menu-row autox-trigrow" +
          (t.planned ? " is-planned" : "") +
          (on ? " is-on" : "")
        }
        // ⛔ A PLANNED ROW IS DISABLED, A NOT-READY ONE IS NOT. `clean_trigger` refuses the first
        // at the door and ACCEPTS the second — readiness is a deployment fact, not a validity
        // one (the engine's own split for `email` and `ig_profile_match`). Disabling both would
        // put a wall in front of a trigger the server would happily store, and the reader would
        // have no way to configure the thing they are about to connect.
        disabled={disabled || !!t.planned}
        title={t.detail || ""}
        onClick={() => onPick(t.key)}
      >
        <span className={"autox-card-mark" + (hasBrandKind(t.key) ? " is-brand" : "")}>
          <TriggerMark kind={t.key} />
        </span>
        <span className="autox-menu-text">
          <span className="autox-menu-label">
            {t.label}
            {rowNote(t) ? <span className="autox-soon">{rowNote(t)}</span> : null}
          </span>
          {/* THE SERVER'S OWN SENTENCE, printed verbatim and never composed with anything — the
              same law that put `detail` on the wire instead of a client blurb table. */}
          {t.detail ? <span className="autox-menu-detail">{t.detail}</span> : null}
        </span>
        {/* The tick is the ONLY thing that says which one is chosen, so it is markup rather than
            a background tint: a tint at rest is indistinguishable from a hover on a surface the
            reader is already moving the mouse across. `aria-selected` carries it for everyone
            else. */}
        {on ? (
          <span className="autox-trigrow-on" aria-hidden="true">
            <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor"
              strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
              <path d="m3.4 8.4 3 3 6.2-6.8" />
            </svg>
          </span>
        ) : null}
      </button>
    );
  };

  return (
    <>
      {groupTriggers(options).map((g) => (
        <div className="autox-menu-group" key={g.key || "_"}>
          {/* An absent caption renders NO heading rather than the group id — a server older than
              this client gets one unlabelled section, which is honest, instead of a heading
              reading "connector" in lower case. */}
          {g.label ? <p className="autox-menu-head">{g.label}</p> : null}
          {g.rows.map(row)}
          {/*
            ⭐⭐ WAVE 30 · ITEM 7 / R3 — THE CONNECTOR NEST IS A COLLAPSED DISCLOSURE NOW.
            The owner, verbatim and for the third wave: *"Only when I click 'Scraper' under each
            automation trigger and actions would I see the option to choose either Instagram OR
            TikTok. That's it."*

            ⛔ WHAT WAS HERE WAS THE COMPLAINT ITSELF, and it was an ASYMMETRY rather than a
            missing feature: this rendered `<div className="autox-menu-sub">` with a `<p>` heading
            — always open, merely indented — while `AutomationBuilder`'s action menu four inches
            away already used exactly the markup below. One menu asked you to click; the other
            showed you everything. So this is not a new pattern, it is the OTHER menu's pattern,
            copied verbatim so the two cannot drift apart again.

            ⚠ `<details>` and not a hand-built disclosure: it opens on Enter and Space with no
            keydown handler, it needs no open/closed state of its own to get wrong, and it is
            CLOSED by default, which is the whole ruling.
            ⚠ The summary wears the same 26px `autox-card-mark` the rows beneath it wear (T19's
            marks). A smaller slot here was the first version and it made the heading look like a
            different KIND of thing from its own children — which is the asymmetry again, one
            level down.
          */}
          {g.sub.map((s) => (
            <details className="autox-menu-nest" key={s.key}>
              <summary className="autox-menu-row autox-menu-sum">
                {brandForConnector(s.key) ? (
                  <span className="autox-card-mark is-brand">{brandForConnector(s.key)}</span>
                ) : null}
                <span className="autox-menu-text">
                  <span className="autox-menu-label">{s.label}</span>
                  <span className="autox-menu-detail">
                    {s.rows.length} trigger{s.rows.length === 1 ? "" : "s"}
                  </span>
                </span>
              </summary>
              {s.rows.map(row)}
            </details>
          ))}
        </div>
      ))}
    </>
  );
}

/**
 * ONE PICKER, TWO PRESENTATIONS.
 *
 * · `menu`  — the open flyout the empty state's "+ Add trigger" box opens. The CALLER owns
 *             whether it is open, because it is anchored to that box.
 * · `field` — the compact control in Properties → Trigger details → Trigger type. It shows the
 *             current choice and opens the same list beneath itself.
 *
 * ⚠ `onPick` IS THE CALLER'S DECISION TO CONFIRM OR NOT. Changing a trigger can invalidate the
 * configuration under it, so the builder asks first when there IS something configured — that
 * rule lives with the automation, not in a picker, and duplicating it here would be a second
 * copy free to disagree with the dialog's own wording.
 */
export default function TriggerPicker({
  variant,
  options,
  value,
  disabled,
  onPick,
  onDismiss,
}: {
  variant: "menu" | "field";
  options: TriggerOption[];
  /** The stored trigger key. `""` = nothing picked yet. */
  value: string;
  disabled: boolean;
  onPick: (key: string) => void;
  /** `menu` only: the caller closes itself. Ignored by `field`, which owns its own popover. */
  onDismiss?: () => void;
}) {
  const [open, setOpen] = useState(false);
  const wrap = useRef<HTMLDivElement | null>(null);
  const picked = selectedTrigger(options, value);

  // ⛔ ESCAPE AND AN OUTSIDE CLICK BOTH CLOSE IT, or the popover is a trap — the shell has
  // already paid for a scrim with no Escape (wave 24: every subsequent click swallowed by an
  // invisible full-screen div). Bound only while open, so the app carries no idle listeners.
  useEffect(() => {
    if (variant !== "field" || !open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    const onDown = (e: MouseEvent) => {
      if (!wrap.current?.contains(e.target as Node)) setOpen(false);
    };
    window.addEventListener("keydown", onKey);
    window.addEventListener("mousedown", onDown);
    return () => {
      window.removeEventListener("keydown", onKey);
      window.removeEventListener("mousedown", onDown);
    };
  }, [variant, open]);

  if (variant === "menu") {
    return (
      <div className="autox-menu is-trigger" role="listbox" aria-label="Trigger">
        <TriggerList
          options={options}
          value={value}
          disabled={disabled}
          onPick={(k) => {
            onPick(k);
            onDismiss?.();
          }}
        />
      </div>
    );
  }

  return (
    <div className="autox-trigfield" ref={wrap}>
      <button
        type="button"
        className="auto-input autox-trigbtn"
        aria-haspopup="listbox"
        aria-expanded={open}
        disabled={disabled}
        onClick={() => setOpen((v) => !v)}
      >
        {/* ⛔ THE STORED KEY IS ALWAYS SHOWN, even when the server did not offer it —
            `selectedTrigger` synthesises a "(not offered here)" row rather than returning null.
            The `<select>` this replaces carried the same guard, and without it a trigger pointed
            at something withheld from this session would LOOK unconfigured and the next patch
            would write the blank over it. */}
        <span
          className={"autox-card-mark" + (hasBrandKind(picked?.key || "") ? " is-brand" : "")}
        >
          <TriggerMark kind={picked?.key || ""} />
        </span>
        <span className="autox-trigbtn-label">
          {picked ? picked.label : "Select a trigger…"}
        </span>
        <span className="autox-trigbtn-caret" aria-hidden="true">
          <svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor"
            strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="m4.4 6.4 3.6 3.6 3.6-3.6" />
          </svg>
        </span>
      </button>
      {open ? (
        <div className="autox-menu is-trigfly" role="listbox" aria-label="Trigger type">
          <TriggerList
            options={options}
            value={value}
            disabled={disabled}
            onPick={(k) => {
              setOpen(false);
              onPick(k);
            }}
          />
        </div>
      ) : null}
    </div>
  );
}
