// ============================================
// Reliq — GitHub Action page
// Public route: /github-action
// ============================================

// Read GitHub URL constants from window (defined in reliq-state.jsx).
// Fallback strings are used during early load before reliq-state.jsx executes.
const GA_REPO_URL        = () => window.RELIQ_GITHUB_REPO_URL        || "https://github.com/reliq-dev/reliq";
const GA_MARKETPLACE_URL = () => window.RELIQ_GITHUB_MARKETPLACE_URL || "https://github.com/marketplace/actions/reliq-scan";

const GitHubActionPage = ({ go }) => {
  const [toastVisible, setToastVisible] = React.useState(false);
  const toastTimer = React.useRef(null);

  const [authed, setAuthed] = React.useState(() =>
    window.reliqAuth ? window.reliqAuth.isAuthed() : false
  );
  React.useEffect(() => {
    const onAuth = (e) => setAuthed(!!e.detail);
    window.addEventListener("reliq-auth-change", onAuth);
    return () => window.removeEventListener("reliq-auth-change", onAuth);
  }, []);

  // ── Canonical workflow YAML ───────────────────────────────────────────────
  // This is the exact snippet shown on the page and available to copy.
  // Secret name: RELIQ_KEY (not RELIQ_API_KEY).
  // File:        ./build/app-release.aab (AAB preferred for Play Store).
  // Stores:      play_store,app_store (full enum values — not shorthand play/app).
  const YAML = `name: Reliq
on:
  push:
    branches: [main]
  pull_request:
jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run Reliq scan
        uses: reliq/scan@v1
        with:
          api_key: \${{ secrets.RELIQ_KEY }}
          file: ./build/app-release.aab
          target_stores: play_store,app_store
          fail_on: critical
          pr_comment: true`;

  const copyWorkflow = () => {
    navigator.clipboard.writeText(YAML).then(() => {
      clearTimeout(toastTimer.current);
      setToastVisible(true);
      toastTimer.current = setTimeout(() => setToastVisible(false), 2500);
    }).catch(() => {});
  };

  const goToDocSection = () => {
    try { sessionStorage.setItem("reliq_scroll_to", "docs-github-action"); } catch (_) {}
    go("/docs");
  };

  // ── API key CTA routing ───────────────────────────────────────────────────
  // Docs page is always public; API key creation requires auth + active plan.
  // Route the user to the appropriate step based on their current product state.
  const getApiKeyPath = () => {
    if (!authed) return "/signin";
    const state = window.reliqSubscription?.getProductState?.() || "";
    if (state === "authenticated_pending_payment") return "/payment";
    if (state === "authenticated_past_due" || state === "authenticated_canceled") return "/billing";
    return "/api";
  };

  const getApiKeyLabel = () => {
    if (!authed) return "Create API key";
    const state = window.reliqSubscription?.getProductState?.() || "";
    if (state === "authenticated_pending_payment") return "Activate plan";
    if (state === "authenticated_past_due") return "Update billing";
    if (state === "authenticated_canceled") return "Renew subscription";
    return "Manage API keys";
  };

  // ── Value bullets ─────────────────────────────────────────────────────────────
  const bullets = [
    "Catches policy blockers before human review — not after rejection.",
    "Posts a scan summary as a PR comment with score, verdict, and critical issues.",
    "Fails the workflow on critical findings so bad builds never reach the store.",
    "Generates a PDF report artifact you can attach to releases or share with legal.",
  ];

  // ── Setup steps ──────────────────────────────────────────────────────────────
  const steps = [
    { ic:"key",     n:"01", h:"Create an API key",      d:"Go to Settings → API & Webhooks in your Reliq dashboard and generate a key with scan write permission." },
    { ic:"lock",    n:"02", h:"Add the secret",          d:"In your GitHub repo, navigate to Settings → Secrets → Actions and add RELIQ_KEY with your key value." },
    { ic:"code",    n:"03", h:"Add the workflow",         d:"Copy the YAML above into .github/workflows/reliq.yml. Adjust the file path to match your build output." },
    { ic:"refresh", n:"04", h:"Push and watch",           d:"Open a pull request or push to main. Reliq runs automatically and posts results directly to your PR." },
  ];

  // ── Config table rows ─────────────────────────────────────────────────────────
  const config = [
    { key:"api_key",          req:true,  def:"—",        desc:"Your Reliq API key. Store it as a GitHub Actions secret — never hard-code it." },
    { key:"file",             req:true,  def:"—",        desc:"Relative path to the APK, AAB, or IPA to scan. Glob patterns are supported." },
    { key:"target_stores",   req:false, def:"play_store,app_store", desc:"Comma-separated list of stores to check against. Options: play_store, app_store, or both." },
    { key:"fail_on",         req:false, def:"critical", desc:"Minimum severity that fails the workflow. Options: critical, warning, info, never." },
    { key:"pr_comment",      req:false, def:"true",     desc:"Post a scan summary as a pull-request comment when triggered by a PR event." },
    { key:"report",          req:false, def:"none",     desc:"Generate a report artifact. Options: pdf, json, none. Uploaded to workflow artifacts." },
    { key:"timeout_minutes", req:false, def:"10",       desc:"Maximum minutes to wait for the scan to complete before the step fails." },
  ];

  // ── Shared style constants ────────────────────────────────────────────────────
  const D = {
    eyebrow: {
      fontFamily:"var(--font-mono)", fontSize:11, letterSpacing:"0.14em",
      textTransform:"uppercase", color:"var(--teal)", marginBottom:10, display:"block",
    },
    h1: {
      fontFamily:"var(--font-display)", fontSize:34, fontWeight:700,
      letterSpacing:"-0.025em", margin:"0 0 10px", color:"var(--fg-0)", lineHeight:1.2,
    },
    h2: {
      fontFamily:"var(--font-display)", fontSize:22, fontWeight:700,
      letterSpacing:"-0.02em", margin:"0 0 10px", color:"var(--fg-0)",
    },
    h3: {
      fontFamily:"var(--font-display)", fontSize:14, fontWeight:600,
      letterSpacing:"-0.005em", margin:"20px 0 6px", color:"var(--fg-0)",
    },
    p: {
      fontSize:14.5, color:"var(--fg-1)", lineHeight:1.78, margin:"0 0 12px",
    },
    inlineCode: {
      fontFamily:"var(--font-mono)", fontSize:13, color:"var(--teal)",
      background:"var(--bg-2)", padding:"1px 5px", borderRadius:4,
    },
    note: {
      background:"var(--teal-bg)", border:"1px solid var(--line-3)",
      borderRadius:"var(--r-sm)", padding:"12px 16px",
      fontSize:13.5, color:"var(--fg-1)", lineHeight:1.65, marginBottom:14,
    },
    divider: {
      borderTop:"1px solid var(--line-1)", margin:"52px 0 44px",
    },
  };

  return (
    <LandingLayout go={go} pageTitle="GitHub Action" contentWidth={940}>

      {/* ── Clipboard toast ── */}
      <div style={{
        position:"fixed", bottom:28, left:"50%", transform:`translateX(-50%) translateY(${toastVisible ? 0 : 12}px)`,
        opacity: toastVisible ? 1 : 0,
        transition:"opacity .2s ease, transform .2s ease",
        background:"var(--fg-0)", color:"var(--bg-0)",
        padding:"9px 20px", borderRadius:999,
        fontFamily:"var(--font-sans)", fontSize:13, fontWeight:500,
        pointerEvents:"none", zIndex:9999, whiteSpace:"nowrap",
        boxShadow:"0 4px 20px rgba(0,0,0,0.18)",
      }}>
        Workflow copied ✓
      </div>

      {/* ── Hero ── */}
      <div style={{marginBottom:52}}>
        <span style={D.eyebrow}>GitHub Action</span>
        <h1 style={D.h1}>Run Reliq before every release.</h1>
        <p style={{...D.p, fontSize:16, maxWidth:580, margin:"0 0 28px"}}>
          Add one workflow step and Reliq will scan every build, post a compliance summary to your PR, and fail the job if critical issues are found — before any human reviewer sees your app.
        </p>
        <div style={{display:"flex", gap:12, flexWrap:"wrap", alignItems:"center"}}>
          <button className="btn btn-primary" onClick={() => go(authed ? "/scan/new" : "/free-scan")}>
            Start scanning <Icon name="arrow-right" size={13} />
          </button>
          <button className="btn btn-ghost" onClick={goToDocSection}>
            View API docs
          </button>
        </div>
      </div>

      {/* ── Value bullets ── */}
      <div style={{
        display:"grid", gridTemplateColumns:"1fr 1fr",
        gap:"10px 32px", marginBottom:52,
      }}>
        {bullets.map((b, i) => (
          <div key={i} style={{display:"flex", gap:10, alignItems:"flex-start"}}>
            <span style={{
              flexShrink:0, width:18, height:18, borderRadius:"50%",
              background:"var(--teal-bg)", border:"1px solid var(--teal)",
              display:"flex", alignItems:"center", justifyContent:"center", marginTop:2,
            }}>
              <Icon name="check" size={10} style={{color:"var(--teal)"}} />
            </span>
            <span style={{fontSize:14, color:"var(--fg-1)", lineHeight:1.65}}>{b}</span>
          </div>
        ))}
      </div>

      {/* ── YAML quick-install block ── */}
      <div style={D.divider} />

      <div style={{marginBottom:52}}>
        <h2 style={D.h2}>Quick install</h2>
        <p style={D.p}>
          Copy the workflow below into <span style={D.inlineCode}>.github/workflows/reliq.yml</span> in your repository. Replace the <span style={D.inlineCode}>file</span> path with the build artifact produced by your CI.
        </p>

        <div style={{
          background:"var(--code-bg)", border:"1px solid var(--line-2)",
          borderRadius:"var(--r-lg)", overflow:"hidden", marginTop:20,
        }}>
          {/* Terminal chrome */}
          <div className="topdot" style={{borderBottom:"1px solid var(--line-2)", borderRadius:0}}>
            <span className="d"></span>
            <span className="d"></span>
            <span className="d"></span>
            <span className="title">.github/workflows/reliq.yml</span>
          </div>

          {/* YAML code */}
          <pre style={{
            fontFamily:"var(--font-mono)", fontSize:12.5, color:"var(--fg-1)",
            lineHeight:1.75, padding:"20px 22px", margin:0,
            overflowX:"auto", whiteSpace:"pre",
          }}>{YAML}</pre>

          {/* Action buttons */}
          <div style={{
            display:"flex", gap:10, padding:"14px 18px",
            borderTop:"1px solid var(--line-2)",
            background:"var(--bg-1)", flexWrap:"wrap",
          }}>
            <button className="btn btn-sm" onClick={copyWorkflow}>
              <Icon name="copy" size={13} /> Copy workflow
            </button>
            <a
              href={GA_MARKETPLACE_URL()}
              target="_blank"
              rel="noopener noreferrer"
              className="btn btn-sm btn-ghost"
              style={{textDecoration:"none", display:"inline-flex", alignItems:"center", gap:6}}
            >
              <Icon name="external-link" size={13} /> GitHub Marketplace
            </a>
            <a
              href={GA_REPO_URL()}
              target="_blank"
              rel="noopener noreferrer"
              className="btn btn-sm btn-ghost"
              style={{textDecoration:"none", display:"inline-flex", alignItems:"center", gap:6}}
            >
              <Icon name="external-link" size={13} /> View on GitHub
            </a>
          </div>
        </div>
      </div>

      {/* ── Setup steps ── */}
      <div style={D.divider} />

      <div style={{marginBottom:52}}>
        <h2 style={D.h2}>Set up in four steps.</h2>
        <p style={{...D.p, marginBottom:28}}>
          From zero to automated compliance checks in under five minutes.
        </p>
        <div className="steps-grid">
          {steps.map(s => (
            <div className="feature-card" key={s.n}>
              <div className="ic"><Icon name={s.ic} size={18} /></div>
              <span className="count">{s.n}</span>
              <h3>{s.h}</h3>
              <p>{s.d}</p>
            </div>
          ))}
        </div>
      </div>

      {/* ── Config reference ── */}
      <div style={D.divider} />

      <div style={{marginBottom:52}}>
        <h2 style={D.h2}>Configuration reference</h2>
        <p style={{...D.p, marginBottom:24}}>
          All inputs are passed under the <span style={D.inlineCode}>with:</span> block of the action step.
        </p>

        <div style={{
          border:"1px solid var(--line-1)", borderRadius:"var(--r-lg)",
          overflow:"hidden",
        }}>
          {/* Table header */}
          <div style={{
            display:"grid", gridTemplateColumns:"180px 70px 90px 1fr",
            padding:"10px 18px",
            background:"var(--bg-2)", borderBottom:"1px solid var(--line-1)",
            fontFamily:"var(--font-mono)", fontSize:11.5, fontWeight:500,
            letterSpacing:"0.04em", color:"var(--fg-2)", textTransform:"uppercase",
          }}>
            <span>Input</span>
            <span>Required</span>
            <span>Default</span>
            <span>Description</span>
          </div>
          {config.map((row, i) => (
            <div key={row.key} style={{
              display:"grid", gridTemplateColumns:"180px 70px 90px 1fr",
              padding:"12px 18px", alignItems:"start",
              background: i % 2 === 0 ? "var(--bg-0)" : "var(--bg-1)",
              borderBottom: i < config.length - 1 ? "1px solid var(--line-1)" : "none",
              fontSize:13.5,
            }}>
              <span style={{fontFamily:"var(--font-mono)", fontSize:12.5, color:"var(--teal)"}}>{row.key}</span>
              <span style={{color: row.req ? "var(--red)" : "var(--fg-3)", fontSize:12.5, paddingTop:1}}>
                {row.req ? "Yes" : "No"}
              </span>
              <span style={{fontFamily:"var(--font-mono)", fontSize:12, color:"var(--fg-2)", paddingTop:1}}>{row.def}</span>
              <span style={{color:"var(--fg-1)", lineHeight:1.6}}>{row.desc}</span>
            </div>
          ))}
        </div>
      </div>

      {/* ── CI failure behaviour ── */}
      <div style={D.divider} />

      <div style={{marginBottom:52}}>
        <h2 style={D.h2}>How CI failures work</h2>
        <p style={D.p}>
          When <span style={D.inlineCode}>fail_on</span> is set, Reliq exits with a non-zero status code if the scan finds any finding at or above that severity. This causes the GitHub Actions step — and the entire job — to fail, blocking merges that require status checks to pass.
        </p>
        <p style={D.p}>
          Pair it with <span style={D.inlineCode}>pr_comment: true</span> so contributors see the exact blockers without leaving GitHub:
        </p>

        <pre style={{
          fontFamily:"var(--font-mono)", fontSize:12.5, color:"var(--fg-1)",
          lineHeight:1.75, background:"var(--code-bg)", border:"1px solid var(--line-2)",
          borderRadius:"var(--r-md)", padding:"16px 20px", margin:"16px 0 24px",
          overflowX:"auto", whiteSpace:"pre",
        }}>{`      - name: Run Reliq scan
        uses: reliq/scan@v1
        with:
          api_key: \${{ secrets.RELIQ_KEY }}
          file: ./build/app-release.aab
          fail_on: critical        # block the job on any critical finding
          pr_comment: true         # post the summary as a PR comment`}</pre>

        <div style={D.note}>
          <strong>Tip:</strong> Use <span style={D.inlineCode}>fail_on: warning</span> during early development and tighten to <span style={D.inlineCode}>fail_on: critical</span> as you approach your release branch. You can also set <span style={D.inlineCode}>fail_on: never</span> to run in observation-only mode.
        </div>

        {/* ── PR comment preview ── */}
        <p style={{...D.p, marginTop:28}}>
          Here's what the PR comment looks like when findings are present:
        </p>

        <div style={{
          border:"1px solid var(--line-2)", borderRadius:"var(--r-lg)",
          overflow:"hidden", maxWidth:540,
        }}>
          {/* Comment header */}
          <div style={{
            padding:"12px 16px", borderBottom:"1px solid var(--line-1)",
            background:"var(--bg-2)",
            display:"flex", alignItems:"center", gap:10,
          }}>
            <div style={{
              width:28, height:28, borderRadius:"50%",
              background:"var(--teal-bg)", border:"1px solid var(--teal)",
              display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0,
            }}>
              <Icon name="activity" size={13} style={{color:"var(--teal)"}} />
            </div>
            <div>
              <span style={{fontWeight:600, fontSize:13, color:"var(--fg-0)"}}>reliq-bot</span>
              <span style={{color:"var(--fg-3)", fontSize:12, marginLeft:8}}>commented just now</span>
            </div>
          </div>

          {/* Comment body */}
          <div style={{padding:"16px 18px", background:"var(--bg-0)"}}>
            {/* Score row */}
            <div style={{
              display:"flex", alignItems:"center", gap:14, marginBottom:14,
              paddingBottom:14, borderBottom:"1px solid var(--line-1)",
            }}>
              <div style={{
                fontFamily:"var(--font-display)", fontSize:26, fontWeight:700,
                color:"var(--fg-0)",
              }}>78<span style={{fontSize:14, fontWeight:500, color:"var(--fg-3)"}}>/100</span></div>
              <div>
                <div style={{
                  fontFamily:"var(--font-mono)", fontSize:10.5, letterSpacing:"0.1em",
                  textTransform:"uppercase", color:"var(--amber)", fontWeight:600,
                }}>NEEDS FIXES</div>
                <div style={{fontSize:12, color:"var(--fg-2)", marginTop:2}}>
                  1&nbsp;critical&nbsp;·&nbsp;4&nbsp;warnings&nbsp;·&nbsp;5&nbsp;info
                </div>
              </div>
            </div>

            {/* Critical blocker */}
            <div style={{
              padding:"10px 13px", borderRadius:"var(--r-sm)",
              background:"rgba(239,68,68,0.07)", border:"1px solid rgba(239,68,68,0.25)",
              marginBottom:12,
            }}>
              <div style={{
                fontFamily:"var(--font-mono)", fontSize:10.5, color:"var(--red)",
                letterSpacing:"0.1em", fontWeight:600, marginBottom:4,
              }}>CRITICAL</div>
              <div style={{fontSize:13, color:"var(--fg-1)", lineHeight:1.55}}>
                <code style={{...D.inlineCode, fontSize:12}}>android:debuggable="true"</code> detected in release manifest — Play Store will reject this build.
              </div>
            </div>

            {/* Report link */}
            <div style={{display:"flex", gap:10, marginTop:14}}>
              <a
                href="#"
                onClick={e => e.preventDefault()}
                style={{
                  fontSize:12.5, color:"var(--teal)", textDecoration:"none",
                  display:"inline-flex", alignItems:"center", gap:5,
                }}
              >
                <Icon name="external-link" size={11} /> View full report →
              </a>
              <span style={{fontSize:12.5, color:"var(--fg-3)"}}>· Posted by Reliq · <a href="#" onClick={e=>e.preventDefault()} style={{color:"var(--fg-3)"}}>Dismiss</a></span>
            </div>
          </div>
        </div>
      </div>

      {/* ── Supported files ── */}
      <div style={D.divider} />

      <div style={{marginBottom:52}}>
        <h2 style={D.h2}>Supported build files</h2>
        <p style={{...D.p, marginBottom:24}}>
          Point the <span style={D.inlineCode}>file</span> input at any of the following artifact types. Glob patterns let you match the output of any build variant.
        </p>

        <div style={{display:"flex", gap:12, flexWrap:"wrap"}}>
          {[
            { ext:"APK", label:"Android APK",       eg:"*.apk",         note:"Universal + split APKs supported" },
            { ext:"AAB", label:"Android App Bundle", eg:"*.aab",         note:"Recommended for Play Store" },
            { ext:"IPA", label:"iOS App Archive",   eg:"*.ipa",         note:"Simulator builds excluded" },
          ].map(f => (
            <div key={f.ext} style={{
              flex:"1 1 200px", padding:"16px 20px",
              border:"1px solid var(--line-2)", borderRadius:"var(--r-lg)",
              background:"var(--bg-1)",
            }}>
              <div style={{
                display:"inline-block", fontFamily:"var(--font-mono)", fontSize:11,
                fontWeight:700, letterSpacing:"0.1em", color:"var(--teal)",
                background:"var(--teal-bg)", border:"1px solid var(--teal)",
                borderRadius:4, padding:"2px 8px", marginBottom:10,
              }}>{f.ext}</div>
              <div style={{fontWeight:600, fontSize:13.5, color:"var(--fg-0)", marginBottom:4}}>{f.label}</div>
              <div style={{fontFamily:"var(--font-mono)", fontSize:12, color:"var(--fg-2)", marginBottom:6}}>{f.eg}</div>
              <div style={{fontSize:12.5, color:"var(--fg-3)"}}>{f.note}</div>
            </div>
          ))}
        </div>
      </div>

      {/* ── Bottom CTA ── */}
      <div style={{
        borderTop:"1px solid var(--line-1)", paddingTop:48, marginTop:0,
        display:"flex", flexDirection:"column", alignItems:"center", textAlign:"center", gap:18,
      }}>
        <h2 style={{...D.h2, fontSize:24, margin:0}}>Ready to automate compliance?</h2>
        <p style={{...D.p, maxWidth:460, margin:0}}>
          Add Reliq to your pipeline today and stop finding out about rejections from App Review.
        </p>
        <div style={{display:"flex", gap:12, flexWrap:"wrap", justifyContent:"center"}}>
          <button className="btn btn-ghost" onClick={goToDocSection}>
            <Icon name="book" size={13} /> Read the docs
          </button>
          <button className="btn btn-primary" onClick={() => go(getApiKeyPath())}>
            <Icon name="key" size={13} /> {getApiKeyLabel()}
          </button>
        </div>
      </div>

    </LandingLayout>
  );
};

Object.assign(window, { GitHubActionPage });
