/* global React */
// MagMapper Interactive Tutorial - section content.

const { useState } = React;

const screenshot = (name) => `assets/screenshots/${name}`;

function ScreenshotPhone({ src, alt, label, height = 420 }) {
  const open = () => {
    if (window.openScreenshotLightbox) {
      window.openScreenshotLightbox(src, alt || label || 'MagMapper screenshot');
    }
  };

  return (
    <figure className="screenshot-phone" style={{ '--shot-height': `${height}px` }}>
      <button
        type="button"
        className="screenshot-button"
        onClick={open}
        aria-label={`Enlarge ${label || alt || 'screenshot'}`}
      >
        <img src={src} alt={alt} loading="lazy" />
      </button>
      {label && <figcaption>{label}</figcaption>}
    </figure>
  );
}

function ScreenGrid({ children, columns = 3 }) {
  return (
    <div className={`screen-grid cols-${columns}`}>
      {children}
    </div>
  );
}

function DetailBox({ title, children, open = false }) {
  return (
    <details className="detail-box" open={open}>
      <summary>{title}</summary>
      <div>{children}</div>
    </details>
  );
}

function Checklist({ items }) {
  return (
    <ul className="check-list">
      {items.map((item) => <li key={item}>{item}</li>)}
    </ul>
  );
}

function MiniPanel({ title, children }) {
  return (
    <div className="mini-panel">
      <h4>{title}</h4>
      <p>{children}</p>
    </div>
  );
}

function SectionAbout() {
  return (
    <section id="about">
      <div className="hero">
        <div>
          <div className="hero-kicker">
            <span className="dot"></span>
            <span>Citizen science - orphan well detection</span>
          </div>
          <h1>MagMapper</h1>
          <p className="hero-sub">
            Use a phone magnetometer to survey suspected oil and gas well sites.
            Walk a grid, record magnetic data, document field conditions, and
            upload the survey for CIRES review.
          </p>
          <div className="hero-stats">
            <div className="stat">
              <div className="stat-val">3.5M+</div>
              <div className="stat-lbl">documented well locations</div>
            </div>
            <div className="stat">
              <div className="stat-val">300K to 800K</div>
              <div className="stat-lbl">estimated undocumented orphaned wells</div>
            </div>
            <div className="stat">
              <div className="stat-val">1000+ nT</div>
              <div className="stat-lbl">well-casing signals</div>
            </div>
          </div>
        </div>
        <div className="hero-visual">
          <ScreenshotPhone
            src={screenshot('20260513_10_survey_mag_map_collected_cells_recording.png')}
            alt="MagMapper Mag tab with collected magnetic grid cells"
            label="Current Mag tab"
            height={500}
          />
        </div>
      </div>
    </section>
  );
}

function SectionSafety() {
  const safetyItems = [
    'Do not enter private land without permission.',
    'Public Lands overlay is informational only; it does not grant access.',
    'Stay away from visible openings, suspect infrastructure, unstable ground, gas odor, and sharp metal.',
    'Keep the phone and survey route away from vehicles, fences, tools, keys, and power equipment where possible.',
    'Avoid recording people, license plates, homes, or private details in photos, audio, and notes unless needed and permitted.',
    'Leave immediately if conditions feel unsafe.'
  ];

  return (
    <section id="safety">
      <div className="sec-kicker">Before you go</div>
      <h2 className="sec-title">Safety and Access</h2>
      <p className="sec-lede">
        MagMapper helps collect field observations, but it does not make a site
        safe or accessible. Treat abandoned well locations as potential hazards.
      </p>
      <div className="safety">
        <div className="safety-icon">!</div>
        <div>
          <h3>Field rules</h3>
          <Checklist items={safetyItems} />
        </div>
      </div>
      <ScreenGrid columns={2}>
        <MiniPanel title="Map layers">
          The home map includes Public Lands, Well Density, Satellite, and Street
          options in the Map Details sheet.
        </MiniPanel>
        <MiniPanel title="Magnetic clutter">
          Strong nearby metal can produce false positives. Document clutter with
          photos and notes so the survey can be interpreted later.
        </MiniPanel>
      </ScreenGrid>
    </section>
  );
}

function SectionStart() {
  const steps = [
    {
      num: '01',
      title: 'Sign in',
      body: 'Use Google sign-in. The sign-in screen also links to the privacy policy.',
      src: '20260513_01_sign_in_google_privacy.png',
      alt: 'MagMapper Google sign-in screen'
    },
    {
      num: '02',
      title: 'Open New map',
      body: 'The signed-in home screen uses New, Surveys, and Awards tabs.',
      src: '20260513_02_home_new_map_satellite_public_lands.png',
      alt: 'MagMapper New tab map with satellite imagery and public land overlay'
    },
    {
      num: '03',
      title: 'Pick a location',
      body: 'Tap a documented well marker, or long-press at close zoom for an unmarked well.',
      src: '20260513_05_home_new_map_selected_well_info_window.png',
      alt: 'Selected well information popup on the New map'
    },
    {
      num: '04',
      title: 'Name the survey',
      body: 'Choose Marked Location or My Location, then enter a 3 to 15 character survey name.',
      src: '20260513_07_new_survey_dialog_marked_well_api.png',
      alt: 'New Survey dialog for a marked well'
    }
  ];

  return (
    <section id="start">
      <div className="sec-kicker">Quick start</div>
      <h2 className="sec-title">Start a survey</h2>
      <p className="sec-lede">
        First-time users only need the main path: sign in, choose or place a
        location, name the survey, and begin recording from the Mag tab.
      </p>
      <div className="steps">
        {steps.map((step) => (
          <div className="step" key={step.num}>
            <div className="step-num"><b>{step.num}</b> step</div>
            <div className="step-title">{step.title}</div>
            <div className="step-body">{step.body}</div>
            <div className="step-visual">
              <ScreenshotPhone
                src={screenshot(step.src)}
                alt={step.alt}
                height={310}
              />
            </div>
          </div>
        ))}
      </div>
      <div className="split">
        <div className="split-copy">
          <h3>Map tools</h3>
          <p>
            Tap the layers button to open Map Details. MagMapper uses ArcGIS/Esri
            map layers: Public Lands is on by default, Well Density is off by
            default, and the base map can switch between Satellite and Street.
          </p>
          <p>
            If you long-press too far zoomed out, the app shows Unmarked Well
            Error and asks you to zoom in for accurate positioning.
          </p>
        </div>
        <div className="screen-row">
          <ScreenshotPhone
            src={screenshot('20260513_03_home_map_details_public_lands_satellite.png')}
            alt="Map Details bottom sheet with Public Lands, Well Density, Satellite, and Street"
            label="Map Details"
            height={390}
          />
          <ScreenshotPhone
            src={screenshot('20260318_android_06_home_unmarked_well_zoom_error.png')}
            alt="Unmarked Well Error dialog asking the user to zoom in"
            label="Zoom error"
            height={390}
          />
        </div>
      </div>
    </section>
  );
}

const strategyGridSize = 11;
const strategyStep = 18;
const strategyOrigin = 12;
const strategyCell = 16;
const strategyCenter = (index) => strategyOrigin + index * strategyStep + strategyCell / 2;

function strategyHeatColor(value) {
  if (value < 0.15) return 'var(--heat-0)';
  if (value < 0.30) return 'var(--heat-1)';
  if (value < 0.45) return 'var(--heat-2)';
  if (value < 0.60) return 'var(--heat-3)';
  if (value < 0.75) return 'var(--heat-4)';
  if (value < 0.90) return 'var(--heat-5)';
  return 'var(--heat-6)';
}

function buildTargetPath() {
  let d = '';
  for (let row = 0; row < strategyGridSize; row++) {
    const y = strategyCenter(row);
    const left = strategyCenter(0);
    const right = strategyCenter(strategyGridSize - 1);
    const start = row % 2 === 0 ? left : right;
    const end = row % 2 === 0 ? right : left;
    d += `${row === 0 ? 'M' : 'L'} ${start},${y} L ${end},${y} `;
  }
  return d.trim();
}

function buildSpiralPoints() {
  const points = [];
  const cx = strategyCenter(5);
  const cy = strategyCenter(5);
  const turns = 3.25;
  const pointsPerTurn = 64;
  const total = Math.floor(turns * pointsPerTurn);
  for (let i = 0; i <= total; i++) {
    const theta = (i / pointsPerTurn) * Math.PI * 2;
    const radius = 3 + 2.85 * theta;
    points.push([
      cx + radius * Math.cos(theta),
      cy + radius * Math.sin(theta)
    ]);
  }
  return points;
}

const targetPath = buildTargetPath();
const spiralPoints = buildSpiralPoints();
const spiralPath = `M ${spiralPoints.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' L ')}`;
const spiralOrder = (() => {
  const order = new Map();
  spiralPoints.forEach(([x, y], index) => {
    const col = Math.floor((x - strategyOrigin) / strategyStep);
    const row = Math.floor((y - strategyOrigin) / strategyStep);
    const key = row * strategyGridSize + col;
    if (
      col >= 0 &&
      col < strategyGridSize &&
      row >= 0 &&
      row < strategyGridSize &&
      !order.has(key)
    ) {
      order.set(key, index);
    }
  });
  return order;
})();

function strategyCells(mode) {
  const known = mode === 'known';
  const peak = known ? { col: 5, row: 5 } : { col: 7, row: 3 };
  const cells = [];
  for (let row = 0; row < strategyGridSize; row++) {
    for (let col = 0; col < strategyGridSize; col++) {
      const key = row * strategyGridSize + col;
      const spiralIndex = spiralOrder.get(key);
      const visited = known || spiralIndex !== undefined;
      const distance = Math.hypot(col - peak.col, row - peak.row);
      const intensity = distance < 1 ? 0.96
        : distance < 2 ? 0.78
        : distance < 3 ? 0.56
        : distance < 4.5 ? 0.34
        : 0.14;
      const serpentineOrder = row * strategyGridSize + (row % 2 === 0 ? col : strategyGridSize - 1 - col);
      const delay = known
        ? (serpentineOrder / (strategyGridSize * strategyGridSize)) * 2.7
        : ((spiralIndex ?? spiralPoints.length) / spiralPoints.length) * 3.2;
      cells.push({ key, row, col, visited, intensity, delay });
    }
  }
  return cells;
}

function StrategyDemo() {
  const [mode, setMode] = useState('known');
  const [replay, setReplay] = useState(0);
  const known = mode === 'known';
  const cells = strategyCells(mode);
  const activePath = known ? targetPath : spiralPath;
  const title = known ? 'Known location: targeted grid' : 'Uncertain location: search, then refine';
  const body = known
    ? 'Use this when casing is visible or the documented coordinates look reliable. Center a small grid on the target and walk steady passes until cells fill evenly.'
    : 'Use this when GPS is uncertain, casing is not visible, or the site is cluttered. Start near the documented point, walk a broader search pattern, then refine around the strongest anomaly.';
  const bullets = known
    ? [
        'Use 1-2 m cells for a tight survey when the target is known.',
        'Grid or zigzag passes are easiest to repeat and review.',
        'Keep walking until weak or small cells are filled.'
      ]
    : [
        'A strong peak is evidence of metal, not proof of a well by itself.',
        'If the anomaly appears off center, collect denser coverage there.',
        'Start a refined survey around the peak when needed.'
      ];

  return (
    <div className="strategy-card">
      <div className="strategy-copy">
        <h3>Choose a survey strategy</h3>
        <p>
          MagMapper does not require a perfect walking path. Pick the approach
          that matches how confident you are in the starting location.
        </p>
        <div className="tabs">
          <button
            className={`tab ${known ? 'active' : ''}`}
            onClick={() => { setMode('known'); setReplay((value) => value + 1); }}
          >
            Known location
          </button>
          <button
            className={`tab ${!known ? 'active' : ''}`}
            onClick={() => { setMode('uncertain'); setReplay((value) => value + 1); }}
          >
            Uncertain location
          </button>
        </div>
        <h4>{title}</h4>
        <p>{body}</p>
        <ul className="strategy-list">
          {bullets.map((item) => <li key={item}>{item}</li>)}
        </ul>
        <button className="replay-button" onClick={() => setReplay((value) => value + 1)}>
          Replay animation
        </button>
      </div>

      <div className="strategy-visuals">
        <div className="strategy-panel">
          <div className="strategy-panel-title">{known ? 'Magnetic data grid' : 'Anomaly appears off center'}</div>
          <svg key={`grid-${mode}-${replay}`} className="strategy-svg" viewBox="0 0 220 220" aria-label="Animated magnetic grid fill">
            {cells.map((cell) => (
              <rect
                key={cell.key}
                className={cell.visited ? 'strategy-cell' : 'strategy-cell-empty'}
                x={strategyOrigin + cell.col * strategyStep}
                y={strategyOrigin + cell.row * strategyStep}
                width={strategyCell}
                height={strategyCell}
                rx="2"
                fill={cell.visited ? strategyHeatColor(cell.intensity) : 'var(--bg-inset)'}
                style={cell.visited ? { animationDelay: `${cell.delay}s` } : undefined}
              />
            ))}
            {!known && (
              <>
                <rect
                  className="strategy-refined"
                  x={strategyOrigin + 5 * strategyStep}
                  y={strategyOrigin + 1 * strategyStep}
                  width={5 * strategyStep - 2}
                  height={5 * strategyStep - 2}
                />
                <g className="strategy-marker delayed" transform={`translate(${strategyCenter(7)}, ${strategyCenter(3)})`}>
                  <circle r="6" />
                  <circle r="2.5" className="strategy-marker-dot" />
                </g>
              </>
            )}
            {known && (
              <g className="strategy-marker" transform={`translate(${strategyCenter(5)}, ${strategyCenter(5)})`}>
                <circle r="6" />
                <circle r="2.5" className="strategy-marker-dot" />
              </g>
            )}
          </svg>
          <div className="strategy-scale"><span>Low</span><span></span><span>High</span></div>
        </div>

        <div className="strategy-panel">
          <div className="strategy-panel-title">Surveyor path</div>
          <svg key={`path-${mode}-${replay}`} className="strategy-svg" viewBox="0 0 220 220" aria-label="Animated surveyor walking path">
            {Array.from({ length: strategyGridSize + 1 }, (_, index) => {
              const pos = strategyOrigin - 1 + index * strategyStep;
              const end = strategyOrigin - 1 + strategyGridSize * strategyStep;
              return (
                <g key={index}>
                  <line className="strategy-grid-line" x1={pos} y1={strategyOrigin - 1} x2={pos} y2={end} />
                  <line className="strategy-grid-line" x1={strategyOrigin - 1} y1={pos} x2={end} y2={pos} />
                </g>
              );
            })}
            <path className="strategy-path" d={activePath} />
            <circle className="strategy-surveyor" r="5">
              <animateMotion dur="3.4s" fill="freeze" path={activePath} />
            </circle>
            {!known && (
              <>
                <g className="strategy-gps" transform={`translate(${strategyCenter(5)}, ${strategyCenter(5)})`}>
                  <path d="M 0,-7 L 4,0 L 0,7 L -4,0 Z" />
                </g>
                <rect
                  className="strategy-refined"
                  x={strategyOrigin + 5 * strategyStep}
                  y={strategyOrigin + 1 * strategyStep}
                  width={5 * strategyStep - 2}
                  height={5 * strategyStep - 2}
                />
              </>
            )}
          </svg>
          <div className="strategy-legend">
            <span><b className="legend-dot path"></b>surveyor</span>
            <span><b className="legend-dot peak"></b>{known ? 'well location' : 'detected peak'}</span>
            {!known && <span><b className="legend-diamond"></b>documented point</span>}
          </div>
        </div>
      </div>
    </div>
  );
}

function SectionCollect() {
  return (
    <section id="collect">
      <div className="sec-kicker">Core field task</div>
      <h2 className="sec-title">Record magnetic data</h2>
      <p className="sec-lede">
        In the survey Mag tab, press record and walk the grid evenly. The app
        bins phone magnetometer readings into grid cells using location data.
      </p>

      <div className="split">
        <div className="screen-row">
          <ScreenshotPhone
            src={screenshot('20260513_09_survey_mag_map_empty_grid_recording.png')}
            alt="Mag tab with empty grid and recording control"
            label="Start recording"
            height={430}
          />
          <ScreenshotPhone
            src={screenshot('20260513_10_survey_mag_map_collected_cells_recording.png')}
            alt="Mag tab with collected magnetic cells and data count"
            label="Cells fill as you walk"
            height={430}
          />
        </div>
        <div className="split-copy">
          <h3>What to watch</h3>
          <Checklist items={[
            'Survey pages use Mag, Notes, Images, and Settings bottom tabs.',
            'The Mag tab shows the grid, color scale, magnetic value, direction arrow, and data count.',
            'The floating record button changes from start to stop while recording.',
            'If you leave the Mag tab while recording, data collection pauses until you return.',
            'A cell is treated as complete at 50 points; incomplete cells draw smaller.',
            'Even coverage improves maps and model results.'
          ]} />
          <div className="info-grid compact-info">
            <MiniPanel title="Default grid">11 x 11 cells</MiniPanel>
            <MiniPanel title="Default cell">2 x 2 m</MiniPanel>
            <MiniPanel title="Sample options">1, 5, or 10 Hz</MiniPanel>
          </div>
        </div>
      </div>

      <StrategyDemo />

      <div className="gps-section">
        <h3>Why the arrow jumps — and what to do about it</h3>
        <p>
          The blue arrow on the map is the phone's best guess of where you
          are. Each GPS fix has a few meters of error, so when you stand
          still the arrow wanders. Walking steadily gives better spatial
          coverage than standing still or chasing the arrow.
        </p>
        <p>
          The magnetometer measures the field at your actual position, but
          the app can only tag each reading with the GPS coordinate it has.
          If GPS is off by a few meters, your reading lands in a neighboring
          cell. In the demo, green is where the user is, blue is the map
          estimate, and orange marks where readings are assigned.
        </p>

        <GPSDemo />

        <h4>Field advice</h4>
        <Checklist items={[
          'Wait briefly before recording if the blue circle is large. Start when it mostly stabilizes.',
          'Walk steadily through the grid. Do not stop to "fill" a cell — standing still stacks readings at one GPS coordinate without improving spatial coverage.',
          'Do not chase the blue arrow if it jumps. Walk your intended path and let the grid fill from recorded positions.',
          'If GPS is poor (arrow jumping more than one cell, or large circle), use 3-5 m cells or make extra passes.'
        ]} />

        <DetailBox title="More GPS details">
          <p>
            In field conditions, phone-reported GPS accuracy has a median of
            about 4 m. The app records GPS accuracy with each sample. Grid
            cell sizes below about 2 m can be undersampled unless the operator
            walks slowly or makes multiple passes. GPS scatter broadens the
            apparent magnetic anomaly, which can bias the model depth estimate
            deeper than the true source.
          </p>
          <p>
            For the strong, broad anomalies tested in the paper, GPS error
            did not usually prevent detection — but localization and model
            accuracy improve with better GPS conditions and multiple passes.
            If GPS quality is poor, add a note or photo so the data can be
            interpreted correctly. Trees, buildings, terrain, and nearby
            structures degrade GPS more than ordinary cloud cover.
          </p>
        </DetailBox>
      </div>
    </section>
  );
}

function SectionSurvey() {
  const tabs = [
    {
      title: 'Notes',
      body: 'Use text notes for site observations and audio notes for quick field narration. The app supports up to 3 audio recordings at 60 seconds each.',
      shots: [
        ['20260513_11_survey_notes_text_paused_notice.png', 'Notes text field with paused-recording notice', 'Text notes'],
        ['202603_iphone_10_survey_notes_audio_recordings.png', 'Audio recordings list in Notes tab', 'Audio notes']
      ]
    },
    {
      title: 'Images',
      body: 'Use photos to document visible infrastructure, hazards, surface conditions, and magnetic clutter. The app supports up to 6 photos.',
      shots: [
        ['20260513_12_survey_images_select_source_dialog.png', 'Image source dialog with Take a Photo and Pick from Gallery', 'Add image'],
        ['202603_iphone_11_survey_images_gallery.png', 'Images tab gallery with site photos', 'Image gallery']
      ]
    },
    {
      title: 'Settings',
      body: 'Use Settings for upload, cell size, grid size, samples per second, display channel, CSV exports, and deleting the survey. CSV export opens the phone email client with the file attached.',
      shots: [
        ['202603_iphone_12_survey_settings_export_controls.png', 'Settings tab with upload, grid, sample rate, display, export, and delete controls', 'Settings']
      ]
    }
  ];

  return (
    <section id="survey">
      <div className="sec-kicker">Field context</div>
      <h2 className="sec-title">Add notes, photos, and settings</h2>
      <p className="sec-lede">
        Magnetic data is strongest when it comes with context. Notes and photos
        help reviewers understand hazards, visible metal, terrain, and access.
      </p>
      <ScreenGrid columns={3}>
        {tabs.map((tab) => (
          <div className="feature-card" key={tab.title}>
            <h3>{tab.title}</h3>
            <p>{tab.body}</p>
            <div className="screen-row">
              {tab.shots.map(([src, alt, label]) => (
                <ScreenshotPhone
                  key={src}
                  src={screenshot(src)}
                  alt={alt}
                  label={label}
                  height={330}
                />
              ))}
            </div>
          </div>
        ))}
      </ScreenGrid>
    </section>
  );
}

function SectionInversion() {
  return (
    <section id="inversion">
      <div className="sec-kicker">Advanced</div>
      <h2 className="sec-title">Graph and model views</h2>
      <p className="sec-lede">
        Graph and Model are advanced field-feedback tools inside the Mag tab.
        Use them to guide repeat coverage in the field, not as a replacement
        for expert interpretation.
      </p>
      <div className="split">
        <div className="screen-row">
          <ScreenshotPhone
            src={screenshot('202603_iphone_06_survey_mag_map_show_model_grid.png')}
            alt="Full survey grid with model square and Show Model enabled"
            label="Full grid + model square"
            height={430}
          />
          <ScreenshotPhone
            src={screenshot('202603_iphone_07_survey_mag_graph_row_profile_show_model.png')}
            alt="Graph view with row profile, Show Range, and Show Model toggles"
            label="Graph"
            height={430}
          />
          <ScreenshotPhone
            src={screenshot('202603_iphone_08_survey_mag_model_inversion_controls.png')}
            alt="Model view with center, diameter, depth, strength, RMS fit, Estimate Center, and Calculate Inversion"
            label="Model"
            height={430}
          />
        </div>
        <div className="split-copy">
          <h3>Model results are estimates</h3>
          <p>
            The on-device model gives quick field feedback using a simplified
            monopole-style approximation. Use it to guide repeat coverage and
            interpretation, not as a guaranteed measurement of casing-top depth.
          </p>
          <Checklist items={[
            '50% overall grid coverage enables the Model button.',
            'About 90% of cells inside the model window are needed to run the model.',
            'If the model window touches the grid edge, all in-grid model-window cells must be filled.',
            'Model depth is an effective magnetic-source depth, not a guaranteed casing-top depth.',
            'Total field is the safest component for current inversion interpretation.'
          ]} />
        </div>
      </div>
      <div className="callout-row">
        <ScreenshotPhone
          src={screenshot('20260318_android_11_survey_model_insufficient_data_dialog.png')}
          alt="Insufficient Data dialog explaining the model grid has too many empty cells"
          label="Insufficient Data"
          height={360}
        />
        <DetailBox title="What Insufficient Data means" open>
          <p>
            The selected model window does not have enough filled cells. Walk more
            within the model area, reduce the model diameter, or collect a more
            even grid before calculating inversion.
          </p>
        </DetailBox>
      </div>
    </section>
  );
}

function SectionUpload() {
  return (
    <section id="upload">
      <div className="sec-kicker">Submit data</div>
      <h2 className="sec-title">Upload and sync surveys</h2>
      <p className="sec-lede">
        Upload from survey Settings, or use Sync with Server from the Surveys
        tab to restore uploaded surveys that are missing locally.
      </p>
      <div className="split">
        <ScreenshotPhone
          src={screenshot('20260513_16_surveys_list_sync.png')}
          alt="Surveys tab with List of Surveys and Sync with Server button"
          label="Surveys list"
          height={460}
        />
        <div className="split-copy">
          <h3>What gets submitted</h3>
          <p>
            Upload sends a survey ZIP to CIRES through the app. The package
            includes survey metadata, magnetic points, device information,
            photos, and audio notes.
          </p>
          <p>
            The Surveys tab shows your local survey list and includes Sync with
            Server, which can restore uploaded surveys that are missing from the
            phone.
          </p>
          <p>
            In survey Settings, the upload button changes between Upload Survey
            to CIRES, Survey Uploaded to CIRES, and Upload Survey Update to CIRES
            depending on the survey status.
          </p>
        </div>
      </div>
    </section>
  );
}

function SectionGamify() {
  return (
    <section id="gamify">
      <div className="sec-kicker">Optional</div>
      <h2 className="sec-title">Awards and profile</h2>
      <p className="sec-lede">
        Awards are useful motivation, but they are secondary to safe fieldwork
        and complete survey context.
      </p>
      <div className="split">
        <div className="screen-row">
          <ScreenshotPhone
            src={screenshot('20260513_14_awards_achievements.png')}
            alt="Awards tab showing achievements"
            label="Achievements"
            height={430}
          />
          <ScreenshotPhone
            src={screenshot('20260513_15_awards_leaderboard.png')}
            alt="Awards tab showing leaderboard with All Time and Monthly toggle"
            label="Leaderboard"
            height={430}
          />
        </div>
        <div className="split-copy">
          <h3>Awards are optional</h3>
          <p>
            The Awards tab shows achievements, leaderboard rankings, All Time
            and Monthly views, pagination, and My Ranking. These features are
            useful motivation, but they are not required for collecting a good
            field survey.
          </p>
          <DetailBox title="Profile side panel">
            <p>
              The profile side panel shows the signed-in account, username, App
              Theme, Send Feedback, Privacy Policy, Sign Out, and app version.
              Theme choices are System, Light, and Dark.
            </p>
          </DetailBox>
        </div>
      </div>
    </section>
  );
}

function SectionTips() {
  const tips = [
    ['Before recording', 'Check safety, permission, GPS/location state, and magnetic clutter before pressing record.'],
    ['False positives', 'Vehicles, fences, tools, keys, power equipment, and other metal can produce strong anomalies.'],
    ['Small cells', 'Cells with fewer than 50 points render smaller. Walk back through them for more coverage.'],
    ['Disabled model', 'The Model button appears after 50% grid coverage; inversion still needs enough model-window cells.'],
    ['Upload', 'Upload sends a survey ZIP over HTTPS through the CIRES server. Sync can restore uploaded surveys later.'],
    ['Calibration', 'On Android, follow the figure-8 calibration prompt if it appears. Phone model and sensor quality affect results.'],
    ['Phone differences', 'Results vary by phone model, field conditions, sensor height, and GPS accuracy.']
  ];
  const faqs = [
    ['Does every phone work the same?',
      'No. Most modern smartphones have a magnetometer, but sensor quality, operating system behavior, GPS, and field conditions affect results.'],
    ['What does MagMapper detect?',
      'It records magnetic anomalies that may be caused by steel casing or other metal. The app does not prove that an anomaly is a well by itself.'],
    ['How big is the default grid?',
      'The default is 11 x 11 cells with 2 x 2 m cells, so the default footprint is about 22 m by 22 m.'],
    ['What should I photograph?',
      'Photograph visible casing, surface equipment, hazards, nearby metal, terrain, and access conditions.'],
    ['What does model depth mean?',
      'It is an effective magnetic-source depth from a simplified model, not a guaranteed physical casing-top depth.'],
    ['Where can I read the privacy policy or request data deletion?',
      <>Read the <a href="https://geomag.colorado.edu/magmapper-privacypolicy" target="_blank" rel="noopener noreferrer">MagMapper Privacy Policy</a>. Delete Survey removes the local copy from this phone. For an uploaded survey, the delete dialog can also delete the CIRES server copy. For account deletion or help with synced data, email <a href="mailto:magmapper@colorado.edu">magmapper@colorado.edu</a>.</>]
  ];
  const [open, setOpen] = useState(0);

  return (
    <section id="tips">
      <div className="sec-kicker">Field tips</div>
      <h2 className="sec-title">Field tips for better surveys</h2>
      <p className="sec-lede">
        These habits make a first-time survey easier to understand and review later.
      </p>
      <div className="tips">
        {tips.map(([title, body]) => (
          <div className="tip" key={title}>
            <h4>{title}</h4>
            <p>{body}</p>
          </div>
        ))}
      </div>

      <h3 style={{ marginTop: 72, marginBottom: 8 }}>Frequently asked questions</h3>
      <div className="faq">
        {faqs.map(([question, answer], index) => (
          <div className={`faq-item ${open === index ? 'open' : ''}`} key={question}>
            <button className="faq-q" onClick={() => setOpen(open === index ? -1 : index)}>
              <span>{question}</span>
              <span className="ic">+</span>
            </button>
            <div className="faq-a" style={{ maxHeight: open === index ? 260 : 0 }}>
              <div className="faq-a-inner">{answer}</div>
            </div>
          </div>
        ))}
      </div>

      <div className="footer">
        <div className="footer-left">
          <strong>CIRES</strong> - University of Colorado Boulder<br/>
          Funded by the U.S. Department of Energy<br/>
          Updated May 14, 2026
        </div>
        <div className="footer-right">
          <a href="mailto:magmapper@colorado.edu">magmapper@colorado.edu</a>
          <span style={{ color: 'var(--fg-dim)' }}>-</span>
          <a href="https://magmapper.app">magmapper.app</a>
          <span style={{ color: 'var(--fg-dim)' }}>-</span>
          <a href="https://geomag.colorado.edu/magmapper-privacypolicy" target="_blank" rel="noopener noreferrer">Privacy Policy</a>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  ScreenshotPhone, ScreenGrid, DetailBox,
  SectionAbout, SectionSafety, SectionStart, SectionCollect, SectionSurvey,
  SectionInversion, SectionUpload, SectionGamify, SectionTips,
});
