/* ============================================================
   PWC EVENTS — Root Cause & Lessons Learned.
   Renders documented events + illustrative scenarios from
   PWC_DATA (same source as the coverage map). Sage-forward:
   calm, sourced, credited — never sensational.
   ============================================================ */
const EV = window.PWC.INV;
const DATA = window.PWC_DATA;

function EventCard({ e }) {
  const documented = !e.illustrative;
  const coverageHref = window.PWC.INV.nav[1].href + "#" + e.id;
  return (
    <article className="ev-card">
      <div className="ev-top">
        <OpChip op={e.operation_type} />
        {e.illustrative
          ? <span className="ev-illus-badge">Illustrative type</span>
          : <span className="ev-illus-badge">{e.state}</span>}
      </div>
      <h3 className="ev-title">{e.title}</h3>
      <div className="ev-meta">
        {documented && e.county
          ? <span>{e.county} County, {e.state}</span>
          : <span>Representative event type</span>}
        {e.sub_basin && <span>· {e.sub_basin}</span>}
        {documented && e.date && <span>· {e.date}</span>}
      </div>
      <p className="ev-summary">{e.summary}</p>
      {documented && e.root_cause && (
        <div className="ev-field">
          <div className="k">Root cause (per the record)</div>
          <div className="v">{e.root_cause}</div>
        </div>
      )}
      <div className="ev-lesson ev-field">
        <div className="k">Lesson learned</div>
        <div className="v">{e.lesson_learned}</div>
      </div>
      <div className="ev-foot">
        {documented && e.source_url
          ? <a className="ev-source" href={e.source_url} target="_blank" rel="noopener noreferrer">
              Source: <u>{e.source_name}</u><IconArrow size={13} />
            </a>
          : <span className="ev-source" style={{ opacity: .7 }}>Not a specific incident</span>}
        {documented && e.show_on_map && e.lat != null && (
          <a className="ev-map-link" href={coverageHref}><IconReticle size={14} /> View on map</a>
        )}
      </div>
    </article>
  );
}

function EventsPage() {
  const [op, setOp] = React.useState("all");
  const [basin, setBasin] = React.useState("all");

  const ops = ["all", ...Object.keys(DATA.OPS)];
  const basins = ["all", ...Array.from(new Set(DATA.events.filter((e) => e.sub_basin).map((e) => e.sub_basin)))];

  // documented first (with coords), then offshore/no-coord documented, then illustrative
  const docs = DATA.events.filter((e) => (op === "all" || e.operation_type === op) && (basin === "all" || e.sub_basin === basin));
  const scen = basin === "all" ? DATA.scenarios.filter((s) => op === "all" || s.operation_type === op) : [];
  const list = [...docs, ...scen];

  return (
    <React.Fragment>
      <PagesStyles />
      <PageHero
        eyebrow="Root cause & lessons learned"
        h1="What well control events actually teach us"
        sub="Real events, honest root cause, and the lessons that matter on the next location. We study how things go wrong so you have fewer reasons to find out firsthand."
        slotId="pwc-events-hero" slotPlaceholder="Drop a calm West Texas field/location photo"
        secondary={{ label: "See the coverage map", href: EV.nav[1].href }}
      >
        <p className="active-note">
          <IconShield size={15} />
          Reviewing a well that's getting away from you right now? <a href={`tel:${EV.tel}`}>Call — don't read.</a>
        </p>
      </PageHero>

      <section className="section">
        <div className="wrap">
          <Reveal>
            <p className="events-intro">
              Most well control events aren't mysteries. They start in places people have seen before — a barrier that was trusted too long, an injection program a mile away, a valve that had been weeping for a while, a step skipped under time pressure. The value isn't in the drama; it's in the pattern. We pull from public records and published investigations — the Texas Railroad Commission, federal safety alerts, and credible reporting — summarize what happened and why, and pull out the lesson you can actually use. Every case credits and links its source so you can read the original.
            </p>
            <p className="events-howto">
              For each event we keep it to five things: what happened, where and when, the operation in play (drilling, completion, workover, production, or a legacy well), the root cause as best the record shows it, and the lesson worth carrying forward. Where the record is incomplete, we say so. We're not assigning blame — we're learning the pattern.
            </p>
          </Reveal>
        </div>
      </section>

      <section className="section alt" style={{ paddingTop: 0 }}>
        <div className="wrap">
          <Reveal className="sec-head" style={{ marginBottom: "28px" }}>
            <p className="eyebrow">The library</p>
            <h2 className="sec-h">Documented events &amp; lifecycle types.</h2>
          </Reveal>

          <Reveal className="filter-bar" as="div">
            {ops.map((o) => (
              <button key={o} className={`chip filter-chip ${op === o ? "active" : ""}`} onClick={() => setOp(o)}>
                {o !== "all" && <span className="chip-dot" style={{ background: OP_COLORS[o] || "var(--steel)" }} />}
                {o === "all" ? "All operations" : DATA.OPS[o].label}
              </button>
            ))}
            <select className="filter-sel" value={basin} onChange={(e) => setBasin(e.target.value)} aria-label="Filter by sub-basin">
              {basins.map((b) => <option key={b} value={b}>{b === "all" ? "All sub-basins" : b}</option>)}
            </select>
          </Reveal>

          {list.length === 0
            ? <p className="ev-summary" style={{ color: "var(--text-2)" }}>No entries match that filter. Clear it to see the full library.</p>
            : <div className="ev-grid">{list.map((e) => <EventCard key={e.id} e={e} />)}</div>}

          <Reveal style={{ marginTop: "40px" }}>
            <p className="attribution">
              Every entry credits and links its primary source. Summaries are our own words and analysis; source text is not republished wholesale. Where the record is incomplete or an investigation is open, we say so. Figures and details are verified against primary records before publishing. Coordinates shown on the map are approximate county/place centroids — not survey locations.
            </p>
          </Reveal>
        </div>
      </section>

      <CtaBand
        heading="If a well is getting away from you right now, stop reading and call."
        sub="And save our number yourself, so you have it before you need it."
        save={true}
      />
    </React.Fragment>
  );
}

Object.assign(window, { EventCard, EventsPage });
