const { SectionHeader, Divider, Card, Button } = window.ECPSDesignSystem_a74b4a;

const WRAP = { maxWidth: 'var(--ecps-max-width)', margin: '0 auto', padding: '0 var(--ecps-gutter)' };
const SECTION = { padding: 'var(--ecps-section-y) 0', scrollMarginTop: 76 };

// Column counts collapse per the design system breakpoints (900 / 720).
// A three-up grid goes 3 → 2 → 1; a two-up grid goes 2 → 1 at 720.
const cols3 = ({ compact, narrow }) => narrow ? '1fr' : compact ? 'repeat(2,1fr)' : 'repeat(3,1fr)';

// Each gap is paired with the real incident that shows it. Dark cards on the
// Deep Tide section; a mono field note under each body cites the case, and two
// carry a tertiary Source link. San Diego was dropped: the Maui case makes the
// attribution argument more forcefully (federal charges). "A visitor", not "the
// offender", in the Maui note: it is an active federal prosecution.
const PROBLEM_CARDS = [
  {
    label: 'Coverage gap', title: 'Nobody is there.',
    body: 'Most violations occur away from any staff member, in places impossible to watch continuously with personnel alone.',
    noteLoc: 'RICHMOND PARK, UK',
    note: 'cyclists through a protected nesting area, deer fed and approached, no staff present to intervene.',
    source: null,
  },
  {
    label: 'Enforcement gap', title: 'No realistic consequence.',
    body: 'Even where rules exist, there is usually no way to identify an offender after the fact, so penalties go unenforced.',
    noteLoc: 'MALIBU, CA',
    note: 'a beachgoer refused to pick up trash. The only outcome was a viral video and a public identity hunt, not enforcement.',
    source: 'https://www.thecooldown.com/outdoors/beach-pollution-video-tiktok-conservation/',
  },
  {
    label: 'Attribution gap', title: 'Footage without a name.',
    body: 'Sensors and footage can show that something happened. They cannot reliably say who did it without a next step.',
    noteLoc: 'LAHAINA, MAUI, HI',
    note: 'a rock was allegedly thrown at an endangered monk seal. A visitor was identified only because bystanders filmed the act. Federal charges followed under the ESA and MMPA.',
    statLoc: 'HAWAII',
    stat: 'Of at least 16 confirmed intentional monk seal killings in 17 years, all but one remain unsolved. The lone prosecution dates to 2009. Source: Honolulu Civil Beat, 15 May 2026.',
    source: 'https://www.justice.gov/usao-hi/pr/washington-man-formally-charged-information-harassing-endangered-monk-seal-hurling-large',
  },
];

function Problem() {
  const vp = window.useViewport();
  return (
    <section id="problem" style={{ ...SECTION, background: 'var(--ecps-deep-tide)' }}>
      <div style={{ ...WRAP, display: 'flex', flexDirection: 'column', gap: 48 }}>
        <SectionHeader onDark eyebrow="The problem" title="Most violations happen where nobody is watching." lede="Reef damage, wildlife harassment, trail litter, heritage-site damage. The pattern repeats everywhere tourism outpaces enforcement capacity." />
        <div style={{ display: 'grid', gridTemplateColumns: cols3(vp), gap: 16 }}>
          {PROBLEM_CARDS.map(c => (
            <Card key={c.label} variant="dark" label={c.label} title={c.title}>
              {c.body}
              <div style={{ marginTop: 14, fontFamily: 'var(--ecps-font-mono)', fontSize: 11.5, lineHeight: 1.7, color: 'var(--ecps-text-on-dark-muted)' }}>
                <span style={{ color: 'var(--ecps-tidal)' }}>{c.noteLoc} · </span>{c.note}
              </div>
              {c.stat && (
                <div style={{ marginTop: 14, fontFamily: 'var(--ecps-font-mono)', fontSize: 11.5, lineHeight: 1.7, color: 'var(--ecps-text-on-dark-muted)' }}>
                  <span style={{ color: 'var(--ecps-tidal)' }}>{c.statLoc} · </span>{c.stat}
                </div>
              )}
              {c.source && (
                <div style={{ marginTop: 14 }}>
                  <a href={c.source} target="_blank" rel="noopener noreferrer" style={{ fontFamily: 'var(--ecps-font-mono)', fontSize: 11.5, color: 'var(--ecps-tidal)', letterSpacing: '0.5px', textDecoration: 'none' }}>Source →</a>
                </div>
              )}
            </Card>
          ))}
        </div>
      </div>
    </section>
  );
}

// Four detection layers, satellite (top) to individual (bottom). Accent is
// tidal for the three automated layers, sandstone for the human-confirmed one,
// mirroring the tier ladder. The mono tool line uses tidal, not kelp: kelp is a
// light-ground color and fails for contrast on this Deep Tide section.
const SYSTEM_LAYERS = [
  { name: 'Site-level', auto: 'Fully automated', tool: 'Tasked satellite imagery', detects: 'Unauthorized vessels and vehicles in no-entry zones; long-term reef, trail, and forest damage', accent: 'var(--ecps-tidal)' },
  { name: 'Zone-level', auto: 'Largely automated', tool: 'Cameras, drones, acoustic sensors, ANPR, geofenced tags', detects: 'Boundary crossings, flagged actions, unauthorized vehicles, off-track driving', accent: 'var(--ecps-tidal)' },
  { name: 'Remote zones', auto: 'Automated, periodic', tool: 'Satellite-uplink GPS tag', detects: 'Continuous location where cellular tags go dark: open water, high-altitude routes', accent: 'var(--ecps-tidal)' },
  { name: 'Individual-level', auto: 'Human-confirmed', tool: 'Ranger evidence + assistive match', detects: 'Attribution of a detected event to a specific visitor', accent: 'var(--ecps-sandstone)' },
];

function System() {
  const { compact } = window.useViewport();
  return (
    <section id="system" style={{ ...SECTION, background: 'var(--ecps-deep-tide)' }}>
      <div style={{ ...WRAP, display: 'flex', flexDirection: 'column', gap: 48 }}>
        <SectionHeader onDark eyebrow="The system" title="Four layers, from satellite to sign-off." lede="Human review is reserved for the cases the law requires, not routine monitoring." />
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {SYSTEM_LAYERS.map((L, i) => (
            <React.Fragment key={L.name}>
              <div style={{ display: 'flex', flexDirection: compact ? 'column' : 'row', gap: compact ? 14 : 28, alignItems: compact ? 'flex-start' : 'center', background: 'var(--ecps-deep-tide-hover)', border: '1px solid var(--ecps-rule-on-dark)', borderLeft: `3px solid ${L.accent}`, padding: '20px 24px' }}>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: 'none', minWidth: compact ? 'auto' : 190 }}>
                  <div style={{ fontFamily: 'var(--ecps-font-label)', fontSize: 'var(--ecps-fs-label)', fontWeight: 700, letterSpacing: 'var(--ecps-ls-label)', textTransform: 'uppercase', color: L.accent }}>{L.auto}</div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <div style={{ fontFamily: 'var(--ecps-font-display)', fontWeight: 500, fontSize: 16, color: 'var(--ecps-shell)' }}>{L.name}</div>
                  <div style={{ fontFamily: 'var(--ecps-font-mono)', fontSize: 13, letterSpacing: '.3px', color: 'var(--ecps-tidal)' }}>{L.tool}</div>
                  <div style={{ fontFamily: 'var(--ecps-font-display)', fontWeight: 400, fontSize: 13, lineHeight: 1.6, color: 'var(--ecps-text-on-dark-muted)' }}>{L.detects}</div>
                </div>
              </div>
              {i < SYSTEM_LAYERS.length - 1 && (
                <div style={{ alignSelf: 'center', width: 2, height: 32, background: 'color-mix(in srgb, var(--ecps-tidal) 30%, transparent)' }} />
              )}
            </React.Fragment>
          ))}
        </div>
      </div>
    </section>
  );
}

function Tiers() {
  const vp = window.useViewport();
  return (
    <section id="tiers" style={{ ...SECTION, background: 'var(--ecps-shell)' }}>
      <div style={{ ...WRAP, display: 'flex', flexDirection: 'column', gap: 48 }}>
        <SectionHeader eyebrow="Rule-based automation" title="Scan the tag. Log the violation. Done." lede="The consequence ladder is fixed. No discretion, no negotiation. The tier is set by the violation, not the officer." />
        <div style={{ display: 'grid', gridTemplateColumns: cols3(vp), gap: 16 }}>
          <Card variant="accent" accent="tidal" label="Tier 1 · Minor" title="Littering, off-trail">Fully automatic. Fine issued the instant it is logged. No queue, no reviewer, ever.</Card>
          <Card variant="accent" accent="sandstone" label="Tier 2 · Moderate" title="Harassment, off-track driving">One-tap confirm. The rule engine pre-fills the case; an officer confirms in seconds.</Card>
          <Card variant="accent" accent="flag" label="Tier 3 · Severe" title="Heritage damage, injury to wildlife">Full review required. The one place the law requires a human before any record is applied.</Card>
        </div>
      </div>
    </section>
  );
}

function Legal() {
  const { narrow } = window.useViewport();
  return (
    <section id="legal" style={{ ...SECTION, background: 'var(--ecps-shell)' }}>
      <div style={{ ...WRAP, display: 'flex', flexDirection: 'column', gap: 48 }}>
        <SectionHeader eyebrow="Built to survive contact with a courtroom" title="Every component has a legal anchor." lede="Nothing here is a novel legal theory. Each piece borrows its precedent from technology already running, tested, and settled somewhere in the world." />
        <div style={{ display: 'grid', gridTemplateColumns: narrow ? '1fr' : 'repeat(2, 1fr)', gap: 16 }}>
          {[['ANPR / license plates', 'The same technology already running speed cameras and toll roads worldwide. Fully automatic enforcement, decades of precedent.'],
            ['Human review at Tier 3', 'GDPR Article 22 and equivalents require human confirmation before a decision with serious legal effect. A legal floor, not a design preference.'],
            ['Future entry screening', 'Built on sovereign immigration discretion, not administrative penalty. It rests on a state\'s broad, established authority over who it admits.'],
            ['Site-specific permits', 'The same model as trekking permits and timed-entry ticketing at Machu Picchu and the Acropolis. Not a new imposition.']].map(([t, b]) => (
            <Card key={t} variant="accent" accent="tidal" label={t}>{b}</Card>
          ))}
        </div>
      </div>
    </section>
  );
}

function Stats() {
  const { narrow } = window.useViewport();
  return (
    <section id="why" style={{ ...SECTION, background: 'var(--ecps-shell)' }}>
      <div style={{ ...WRAP, display: 'flex', flexDirection: 'column', gap: 48 }}>
        <SectionHeader eyebrow="Why now" title="The revenue exists. The enforcement doesn't." />
        <div style={{ display: 'grid', gridTemplateColumns: narrow ? '1fr' : 'repeat(3,1fr)', gap: 16 }}>
          <Card variant="stat" label="Entry fees" title="$50M">generated annually in one national park system's entry fees</Card>
          <Card variant="stat" label="Reaches conservation" title="~5%">of that revenue reaches direct conservation activity</Card>
          <Card variant="stat" label="Lake Nakuru" title="Zero">rhinos poached since automated camera installation</Card>
        </div>
        <Divider />
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
          <Button variant="inverse" onClick={() => { const el = document.querySelector('#pilot'); if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 76, behavior: 'smooth' }); }}>Request a pilot briefing</Button>
        </div>
      </div>
    </section>
  );
}
Object.assign(window, { Problem, System, Tiers, Legal, Stats });
