// =================================================================
// pw-signin-readiness.jsx — Operator · reader sign-in readiness checklist (Publisher Config)
//
// Reads GET /admin/v1/publishers/:id/sign-in-readiness. Read-only: it says which of the four pieces
// email sign-in needs is missing (site key origin, API key, CORS origin, email sending) and links to
// where each is fixed. It changes nothing itself.
//
// Demo mode reads `signInReadiness` from paywall-data.js; a publisher not listed there shows ready.
// =================================================================

const SIGNIN_DOC = "https://github.com/xpcovertech/dropcap/blob/main/docs/reader-signin-setup.md";

// Where each check is fixed. The site key's origins are edited in the publisher's own Integration
// kits screen; the other three are deployment or provisioning steps described in the runbook.
const SIGNIN_FIX_LINKS = {
  site_key_origin: { label: "Open Integration kits", route: "integration-kits" },
  api_key: { label: "How to issue an API key", href: `${SIGNIN_DOC}#api-key` },
  cors_origin: { label: "How to set CORS_ALLOW_ORIGINS", href: `${SIGNIN_DOC}#cors` },
  email_sending: { label: "How to configure email", href: `${SIGNIN_DOC}#email` },
};

const SIGNIN_DEMO_READY = {
  ready: true, origins: ["https://example.com"], cors_missing_origins: [],
  checks: [
    { id: "site_key_origin", ok: true, label: "Active site key with a registered origin", fix: null },
    { id: "api_key", ok: true, label: "Active publisher API key", fix: null },
    { id: "cors_origin", ok: true, label: "Site origin allowed by the API's CORS list", fix: null },
    { id: "email_sending", ok: true, label: "Email sending configured", fix: null },
  ],
};

const SignInReadinessCard = ({ data, publisherId }) => {
  const live = Boolean(window.__api.getConfig().live);
  const [state, setState] = React.useState({ loading: true, error: null, view: null });

  const load = React.useCallback(async () => {
    if (!publisherId) { setState({ loading: false, error: null, view: null }); return; }
    if (!live) {
      setState({ loading: false, error: null, view: (data.signInReadiness || {})[publisherId] || SIGNIN_DEMO_READY });
      return;
    }
    setState((s) => ({ ...s, loading: true }));
    try {
      const res = await window.__api.call("adminGetSignInReadiness", { params: { publisher_id: publisherId } });
      setState({ loading: false, error: null, view: res });
    } catch (e) {
      setState({ loading: false, error: e && e.status === 403 ? "This publisher is not assigned to you." : "Could not load sign-in readiness.", view: null });
    }
  }, [live, publisherId, data.signInReadiness]);
  React.useEffect(() => { load(); }, [load]);

  const v = state.view;
  const badge = !v ? null : v.ready ? <Pill tone="good">Ready</Pill> : <Pill tone="warn">Not ready</Pill>;

  return (
    <Card title="Reader sign-in" subtitle="Email sign-in (magic link) readiness for this publisher's sites." action={badge}>
      {state.loading ? (
        <div style={{ color: "var(--muted)", fontSize: 13 }}>Checking…</div>
      ) : state.error ? (
        <Banner tone="warn">{state.error}</Banner>
      ) : !v ? null : (
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {v.checks.map((c) => {
            const link = SIGNIN_FIX_LINKS[c.id];
            return (
              <div key={c.id} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                <span aria-hidden="true" style={{ fontWeight: 700, color: c.ok ? "var(--good)" : "var(--warn)", width: 14 }}>{c.ok ? "✓" : "!"}</span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, color: "var(--ink)" }}>{c.label}</div>
                  {!c.ok && c.fix ? <div style={{ fontSize: 12.5, color: "var(--ink-2)", marginTop: 2 }}>{c.fix}</div> : null}
                  {!c.ok && link ? (
                    <div style={{ fontSize: 12.5, marginTop: 4 }}>
                      {link.route
                        ? <a href={`#/${link.route}`} onClick={(e) => { e.preventDefault(); window.__nav(link.route); }}>{link.label}</a>
                        : <a href={link.href} target="_blank" rel="noopener noreferrer">{link.label}</a>}
                    </div>
                  ) : null}
                </div>
              </div>
            );
          })}
          {v.origins && v.origins.length > 0 ? (
            <div style={{ fontSize: 12, color: "var(--muted)" }}>Registered origins: <span style={{ fontFamily: "var(--mono)" }}>{v.origins.join(", ")}</span></div>
          ) : null}
        </div>
      )}
    </Card>
  );
};

Object.assign(window, { SignInReadinessCard });
