/* global React */

/* ─────────────────────────── v05a — Help & Docs page ──────────────────────
   Extracted out of Views.jsx in v05i. ~325 lines of in-line documentation
   prose were being transpiled by Babel-standalone on every page load
   even when the user never opened the Help page. Moved to its own
   script so the index page's transpile budget drops accordingly.
   ----------------------------------------------------------------------- */

const HELP_SECTIONS = [
  { id: "getting-started", label: "Getting started" },
  { id: "shotlist",        label: "Using the shotlist" },
  { id: "setup",           label: "First-time setup" },
  { id: "users",           label: "User management" },
  { id: "folder-watcher",  label: "Folder watcher" },
  { id: "calendar",        label: "Google Calendar" },
  { id: "webhook",         label: "Claude webhook" },
];

function HelpDocsView() {
  const [active, setActive] = React.useState("getting-started");
  const jumpTo = (id) => {
    setActive(id);
    const el = document.getElementById("help-" + id);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  React.useEffect(() => {
    const els = HELP_SECTIONS.map(s => document.getElementById("help-" + s.id)).filter(Boolean);
    if (!els.length) return;
    const io = new IntersectionObserver((entries) => {
      const visible = entries.filter(e => e.isIntersecting).sort((a, b) => b.intersectionRatio - a.intersectionRatio);
      if (visible[0]) {
        const id = visible[0].target.id.replace(/^help-/, "");
        setActive(id);
      }
    }, { rootMargin: "-30% 0px -55% 0px", threshold: [0, 0.25, 0.5, 1] });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
  return (
    <section className="view-page help-view">
      <div className="vp-head">
        <div>
          <div className="vp-eyebrow">HELP &amp; DOCS</div>
          <div className="vp-title">How Film Tracker works</div>
        </div>
      </div>

      <div className="help-layout">
        <aside className="help-nav glass">
          <div className="help-nav-eyebrow">ON THIS PAGE</div>
          {HELP_SECTIONS.map(s => (
            <button
              key={s.id}
              type="button"
              className={"help-nav-item" + (active === s.id ? " is-active" : "")}
              onClick={() => jumpTo(s.id)}
            >{s.label}</button>
          ))}
          <div className="help-nav-foot">
            Trouble with an integration? See <a href="#" onClick={(e) => { e.preventDefault(); window.__navigate && window.__navigate("admin"); }}>Admin → Integrations</a> for live status.
          </div>
        </aside>

        <article className="help-content glass">
          <section id="help-getting-started" className="help-section">
            <h2 className="help-h">Getting started</h2>
            <p>
              Film Tracker is a single-page production tracker for film and VFX projects.
              Everything lives in one window: the project header at the top, a sidebar
              for navigation on the left, the main work area in the middle, and a
              context column for milestones, activity, and notes on the right.
            </p>
            <p>
              You won't lose any work between sessions — the page state, the active view,
              your theme, and your filters all persist in your browser, and project data
              lives in a SQLite database on the server. Hard-refresh with
              <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>R</kbd> after any visual change to
              clear cached assets.
            </p>
            <h3 className="help-h3">The five pages you will use most</h3>
            <ul className="help-list">
              <li><strong>Overview</strong> — the dashboard. Donut + 4 stat cards in the
                top bar, the active shot list in the middle, the calendar and milestones
                on the right.</li>
              <li><strong>Shots</strong> — the full shotlist with filters and sorts.
                Same row design as the Overview's middle column, just without the
                project-wide chrome.</li>
              <li><strong>Assets</strong> — one tab per asset category the project declares
                (for a film documentary: characters, animals, locations, props).
                Each card opens a detail modal with all generations + notes.</li>
              <li><strong>Schedule</strong> — your project's milestones imported
                from Google Calendar (when wired up).</li>
              <li><strong>Settings</strong> — appearance, preferences, notifications,
                and user management for admins.</li>
            </ul>
            <h3 className="help-h3">Sign in</h3>
            <p>
              Sign in with the admin account you were given, then change its password from
              <em> Settings → Preferences → Change password</em>. Additional users can
              be invited from <em>Admin → User management</em>.
            </p>
          </section>

          <section id="help-shotlist" className="help-section">
            <h2 className="help-h">Using the shotlist</h2>
            <p>
              Every shot in your project is one row. Click any row to open the shot
              modal — it has the full prompt, the version history filmstrip
              (frames on top, video underneath), the pipeline stepper, notes, and
              the reference panel.
            </p>
            <h3 className="help-h3">Pipeline stages</h3>
            <p>The seven canonical stages, in order:</p>
            <ol className="help-list">
              <li><strong>Prompt</strong> — text-only spec; no images yet.</li>
              <li><strong>First Pass</strong> — initial concept frames generated.</li>
              <li><strong>Frame WIP</strong> — refinements, exploration variants.</li>
              <li><strong>Frame Hero</strong> — the locked still you will animate.</li>
              <li><strong>Video WIP</strong> — video prompts being iterated.</li>
              <li><strong>Video Hero</strong> — the approved final video.</li>
              <li><strong>4K Upscale</strong> — delivered upscaled master.</li>
            </ol>
            <p>
              Promoting a shot from one stage to the next is "telescoping": setting
              the active stage marks every earlier stage <em>done</em> and clears
              every later stage. The status pill on each row reflects the highest
              stage reached.
            </p>
            <h3 className="help-h3">Shot row thumbnails</h3>
            <p>
              When a shot has a video, the row thumbnail shows the video's first
              frame. Hover the row to start playback. You can change this behaviour
              in <em>Settings → Preferences → Auto-play thumbnail video</em>:
            </p>
            <ul className="help-list">
              <li><strong>All</strong> — every shot animates continuously.</li>
              <li><strong>Hover</strong> — plays only when you hover (default).</li>
              <li><strong>None</strong> — pure static first frames.</li>
            </ul>
            <h3 className="help-h3">Filters &amp; sort</h3>
            <p>
              The Sort and Filter buttons above the shot list cover the common cuts:
              by sequence, by status pill, by archive presence, by who last edited.
              Filters are sticky — they persist across sessions until you clear them.
            </p>
            <h3 className="help-h3">Adding shots</h3>
            <p>
              Producers and admins can add shots directly from the Shots panel
              header. The full create flow includes shot id, sequence, type,
              landscape description, behaviour notes, and the initial reference
              assets. Webhooks and the folder watcher can both create shots
              automatically when they detect new content.
            </p>
          </section>

          <section id="help-setup" className="help-section">
            <h2 className="help-h">First-time setup</h2>
            <p>
              Film Tracker has four optional integrations. None are required, but each
              unlocks an automation that saves a lot of manual work. Configure them
              by editing the project's <code>.env</code> file, then restart the
              server. The <a href="#" onClick={(e) => { e.preventDefault(); window.__navigate && window.__navigate("admin"); }}>
              Admin → Integrations</a> card shows live status for all four.
            </p>
            <p>For the complete walkthrough with credential-fetch screenshots, see <code>docs/SETUP_GUIDE.md</code> in the project repo.</p>

            <h3 className="help-h3">Quick checklist</h3>
            <ol className="help-list help-checklist">
              <li>Copy <code>.env.example</code> → <code>.env</code> at the project root.</li>
              <li>Set <code>WATCH_PATH</code> to your project root folder.</li>
              <li>Generate a <code>WEBHOOK_SECRET</code> string for Claude to authenticate with.</li>
              <li>(Optional) Wire up Cloudflare R2 if you need cloud asset URLs.</li>
              <li>(Optional) Connect Google Calendar to import shoot dates.</li>
              <li>Restart the server. Verify each line in <em>Admin → Integrations</em>.</li>
            </ol>

            <h3 className="help-h3">Why each integration matters</h3>
            <ul className="help-list">
              <li><strong>Folder watcher</strong> — saves you from manually uploading every render. Drop the file into the right folder and it appears in the Media page within seconds.</li>
              <li><strong>Claude webhook</strong> — turns generation events into live Activity Log entries. Combined with the folder watcher you get a fully autonomous pipeline.</li>
              <li><strong>Cloudflare R2</strong> — makes the deployed web version usable from anywhere by uploading renders to a public CDN.</li>
              <li><strong>Google Calendar</strong> — your producer keeps the shoot dates in Calendar anyway; this just imports them so Film Tracker can show them on the Schedule view.</li>
            </ul>
          </section>

          <section id="help-users" className="help-section">
            <h2 className="help-h">User management</h2>
            <p>
              Open <a href="#" onClick={(e) => { e.preventDefault(); window.__navigate && window.__navigate("admin"); }}>
              Admin → User Management</a> to invite, suspend, change roles, or
              delete teammates. You need the <strong>Admin</strong> role to
              see this panel. Permissions for every other role are configured
              just below in the <em>Permissions Matrix</em> — click any cell
              to toggle it.
            </p>

            <h3 className="help-h3">Inviting a new user</h3>
            <ol className="help-list">
              <li>Scroll to the <strong>INVITE NEW USER</strong> form at the bottom of the User Management card.</li>
              <li>Enter their email (required), display name (optional), and pick a role: <em>Reviewer</em>, <em>Tester</em>, <em>Editor</em>, <em>Producer</em>, or <em>Admin</em>.</li>
              <li>Click <strong>Send invite</strong>. A 12-character temporary password appears <strong>once</strong> at the top of the panel.</li>
              <li>Send the email + temp password to the person securely (e.g. 1Password share, Signal). It is <strong>not</strong> stored in plaintext — if you close the dialog before copying it, you'll need to delete and re-invite.</li>
              <li>On first login they're prompted to set their own password.</li>
            </ol>

            <h3 className="help-h3">Roles at a glance</h3>
            <ul className="help-list">
              <li><strong>Admin</strong> — every permission. Bypasses the permissions matrix. Can manage users + integrations. Used for the studio owner / lead producer.</li>
              <li><strong>Producer</strong> — full project control except admin/billing. Can edit shots, approve work, upload, generate, manage schedule. Cannot manage users.</li>
              <li><strong>Editor</strong> — day-to-day production user. Can change shot status, upload assets, comment, but typically not approve or rename shots.</li>
              <li><strong>Reviewer</strong> — read-mostly. Can leave notes, comment on review videos, and mark approval, but can't edit shotlist or upload renders.</li>
              <li><strong>Tester</strong> — locked-down. View-only on most pages. Used for outside collaborators or QA accounts.</li>
            </ul>
            <p>
              The exact gates are visible (and editable) in the Permissions Matrix
              below the user table. <em>Admin</em> always wins regardless of
              what the matrix says — that row is a no-op.
            </p>

            <h3 className="help-h3">Suspend vs delete</h3>
            <ul className="help-list">
              <li><strong>Suspend</strong> — reversible. The account stays in the DB, all their notes/comments stay attached, but they can no longer log in. Click <em>Reactivate</em> to restore.</li>
              <li><strong>Delete</strong> — permanent. The user row is removed and all of their authored notes/comments/uploads keep a <em>(removed user)</em> label. You'll see a confirm step before it actually deletes.</li>
            </ul>
            <p className="help-note">
              You can't delete the account you're logged in as — Film Tracker
              would lock you out instantly. Sign in as another admin first.
            </p>

            <h3 className="help-h3">Resetting someone's password</h3>
            <p>
              In <em>Admin → User Management</em>, the temp-password flow doubles
              as a reset: delete the row, re-invite the email, share the new
              temp.
            </p>
          </section>

          {/* 23 Sep 2026 — the "Email notifications (SMTP)" section was removed with the email feature. */}

          <section id="help-folder-watcher" className="help-section">
            <h2 className="help-h">Folder watcher</h2>
            <p>
              The folder watcher monitors a directory on disk for new renders.
              When a fresh image or video appears in the expected layout, Film
              Tracker auto-creates an <code>asset_versions</code> row, attaches
              it to the correct shot, and surfaces it in the version filmstrip
              and Media page — no upload, no manual import.
            </p>
            <h3 className="help-h3">Configuration</h3>
            <p>In <code>.env</code>:</p>
            <pre className="help-code">WATCH_PATH=&lt;your project root&gt;</pre>
            <p>Point at the <strong>project root</strong>, not the shots folder.</p>
            <h3 className="help-h3">Folder layout</h3>
            <p>The watcher expects this flat structure (sequence is looked up from the DB by shot id):</p>
            <pre className="help-code">{`<WATCH_PATH>/SHOT_<NNNN>/<kind>_v<NN>.<ext>

Example:
<your project root>\\
   SHOT_0010\\
      image_v03.png
      video_v01.mp4
      concept_v05.jpg`}</pre>
            <ul className="help-list">
              <li><code>SHOT_NNNN</code> — four-digit shot number; becomes <code>SH&lt;NNNN&gt;</code> in the DB.</li>
              <li><code>&lt;kind&gt;</code> — free text (e.g. <em>image</em>, <em>concept</em>, <em>final</em>, <em>video</em>).</li>
              <li><code>vNN</code> — version number; stored as <code>version_label = "vNN"</code>.</li>
              <li>Image extensions: <code>.jpg .jpeg .png .webp .tiff</code></li>
              <li>Video extensions: <code>.mp4 .mov .avi</code></li>
            </ul>
            <p>Files that do not match the pattern are silently ignored — feel free to drop notes, PSDs, or scratch renders next to the real assets.</p>
            <h3 className="help-h3">Verifying it is running</h3>
            <ol className="help-list">
              <li>Look in the server console for <code>[folderWatcher] watching &lt;path&gt;</code>.</li>
              <li>Open <em>Admin → Integrations</em>. Folder Watcher should be green.</li>
              <li>Drop a test render. It should appear in the Media page within 1–2 seconds.</li>
            </ol>
          </section>

          <section id="help-calendar" className="help-section">
            <h2 className="help-h">Google Calendar</h2>
            <p>
              Connecting Google Calendar imports events from a chosen calendar
              into the Schedule view. The sync runs every 15 minutes, plus once
              on every server boot, plus on demand from the Schedule page.
            </p>
            <h3 className="help-h3">Configuration</h3>
            <p>In <code>.env</code>:</p>
            <pre className="help-code">{`GOOGLE_CLIENT_ID=<client_id>.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=<client_secret>
GOOGLE_REFRESH_TOKEN=<refresh_token>
GOOGLE_CALENDAR_ID=primary`}</pre>
            <h3 className="help-h3">Getting the credentials</h3>
            <ol className="help-list">
              <li>Open <a href="https://console.cloud.google.com" target="_blank" rel="noreferrer">Google Cloud Console</a> → APIs &amp; Services → Credentials.</li>
              <li>Create an OAuth 2.0 Client ID. Application type: "Web application".</li>
              <li>Add <code>http://localhost:3001/api/calendar/auth/callback</code> to the Authorised redirect URIs list.</li>
              <li>Copy the Client ID and Client Secret into <code>.env</code>.</li>
              <li>Open <code>http://localhost:3001/api/calendar/auth</code> in your browser. Approve the calendar read scope.</li>
              <li>The redirect prints a refresh token in the server console. Paste it into <code>GOOGLE_REFRESH_TOKEN</code>.</li>
              <li>Set <code>GOOGLE_CALENDAR_ID</code> to <code>primary</code>, or your specific calendar id (Google Calendar → Settings → Integrate calendar → Calendar ID).</li>
            </ol>
            <h3 className="help-h3">Connecting from the UI</h3>
            <p>
              The Calendar panel on the right column has a <em>Connect Google
              Calendar</em> button. If the server-side credentials are missing
              it surfaces a friendly "Not configured yet" message inside the
              modal — finish the env setup above before retrying.
            </p>
          </section>

          <section id="help-webhook" className="help-section">
            <h2 className="help-h">Claude webhook</h2>
            <p>
              The Claude webhook is a single HTTP endpoint that lets Claude or
              Cowork push generation events to Film Tracker in real time. When
              an image or video finishes rendering, Claude calls the webhook
              and the UI updates instantly — no polling, no manual refresh.
            </p>
            <h3 className="help-h3">Configuration</h3>
            <p>In <code>.env</code>, set a shared secret of your choice:</p>
            <pre className="help-code">WEBHOOK_SECRET=replace-with-random-32-char-string</pre>
            <p>
              Any random string works. Generate one with
              <code> openssl rand -hex 16 </code>
              or use a password manager's "generate" feature.
            </p>
            <h3 className="help-h3">Endpoint</h3>
            <pre className="help-code">{`POST  http://localhost:3001/api/webhook/claude        (dev)
POST  https://<your-host>/api/webhook/claude         (prod)

Headers:
  Content-Type: application/json
  X-Webhook-Secret: <WEBHOOK_SECRET>

Body:
{
  "shot_id":    "SH0010",
  "action":     "image_completed",
  "file_path":  "work/episodes/<episode>/shots/SH0010/frames/SH0010_frame_v005_f1.png",
  "version_label": "v005_f1",
  "model":      "nano-banana-pro",
  "prompt":     "MACRO CLOSE-UP: ..."
}`}</pre>
            <h3 className="help-h3">Valid actions</h3>
            <ul className="help-list">
              <li><code>image_started</code> — generation begins; shot enters rendering state.</li>
              <li><code>image_completed</code> — image is ready; creates an asset_version row.</li>
              <li><code>video_started</code> — video generation begins.</li>
              <li><code>video_completed</code> — video is ready; creates an asset_version row.</li>
              <li><code>shot_updated</code> — generic edit (status change, note added, etc.).</li>
            </ul>
            <h3 className="help-h3">Verifying the webhook is wired up</h3>
            <ol className="help-list">
              <li>Send a test request from your terminal using the curl example above.</li>
              <li>Check the Activity Log — the call should appear within a second.</li>
              <li>Open <em>Admin → Integrations</em>. Claude Webhook should be green.</li>
            </ol>
            <p>Full reference for the payload and error responses: <code>docs/webhook-format.md</code>.</p>
          </section>
        </article>
      </div>
    </section>
  );
}

Object.assign(window, { HelpDocsView });
