/* ================================================================
   login.jsx — Capital Economics sign-in page.
   Two layout variants (A: stacked single column, preferred; B:
   asymmetric two-column) plus the six sign-in card states, laid
   out on a design canvas for comparison. Header/footer, tokens,
   button + field styles inherited from the Sprint 1 system
   (shared.jsx + the CE design-system bundle).

   Hierarchy rule that governs the whole page: exactly one obvious
   primary action. "Sign in" is the solid primary. "Start free
   trial" is a secondary (outline) treatment so an existing client
   never has to scan past marketing to reach the email field.
================================================================ */
const { Button, Input } = window.CapitalEconomicsDesignSystem_f2a5b2;
const { SiteHeader, SiteFooter, NS, SERIF } = window;
const { DesignCanvas, DCSection, DCArtboard, DCPostIt } = window;

/* ---- Icons (Lucide subset, 24x24, 2px stroke) ---- */
const LICONS = {
  eye: <><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z" /><circle cx="12" cy="12" r="3" /></>,
  "eye-off": <><path d="M10.7 5.1A9.9 9.9 0 0 1 12 5c6.5 0 10 7 10 7a13.2 13.2 0 0 1-2.2 2.9" /><path d="M6.6 6.6A13.3 13.3 0 0 0 2 12s3.5 7 10 7a9.7 9.7 0 0 0 5.4-1.6" /><path d="m2 2 20 20" /><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2" /></>,
  check: <path d="M20 6 9 17l-5-5" />,
  "arrow-right": <><path d="M5 12h14" /><path d="m12 5 7 7-7 7" /></>,
  "alert-circle": <><circle cx="12" cy="12" r="10" /><path d="M12 8v4M12 16h.01" /></>,
  "check-circle": <><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" /><path d="m9 11 3 3L22 4" /></>,
  phone: <path d="M13.83 19.05A16 16 0 0 1 4.95 10.17 2 2 0 0 1 6.9 7.86l1.27-.2a2 2 0 0 1 2.2 1.28l.5 1.37a2 2 0 0 1-.55 2.16l-.7.62a12 12 0 0 0 4 4l.62-.7a2 2 0 0 1 2.16-.55l1.37.5a2 2 0 0 1 1.28 2.2l-.2 1.27a2 2 0 0 1-2.31 1.95z" />,
  mail: <><rect width="20" height="16" x="2" y="4" rx="2" /><path d="m22 7-10 6L2 7" /></>,
  clock: <><circle cx="12" cy="12" r="10" /><path d="M12 6v6l4 2" /></>,
  loader: <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83" />,
};
function LIcon({ name, size = 20, stroke = 2, style }) {
  return (
    <svg style={style} width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      {LICONS[name]}
    </svg>
  );
}

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

/* One-time CSS for pieces the DS components don't cover. */
let loginCSSInjected = false;
function injectLoginCSS() {
  if (loginCSSInjected || typeof document === "undefined") return;
  loginCSSInjected = true;
  const css = `
  .lg-quietlink { font-family: ${NS}; font-size: 14px; font-weight: 600; color: var(--text-link); text-decoration: none; background: none; border: 0; padding: 0; cursor: pointer; }
  .lg-quietlink:hover { text-decoration: underline; }
  .lg-pwtoggle { appearance: none; border: 0; background: transparent; color: var(--text-muted); display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; border-radius: var(--radius-sm, 4px); cursor: pointer; }
  .lg-pwtoggle:hover { color: var(--text-secondary); }
  .lg-pwtoggle:focus-visible { outline: 0; box-shadow: var(--ring-focus); }
  .lg-spin { animation: lgspin 0.7s linear infinite; }
  @keyframes lgspin { to { transform: rotate(360deg); } }
  .lg-banner { display: flex; gap: 11px; align-items: flex-start; border-radius: var(--radius-md); padding: 13px 15px; font-family: ${NS}; font-size: 14px; line-height: 1.45; margin-bottom: 22px; }
  .lg-banner-err { background: var(--negative-100, #fdecea); color: var(--negative-700, #a02c22); border: 1px solid var(--negative-200, #f5c6c0); }
  .lg-banner-ok { background: var(--positive-100, #e7f4ec); color: var(--positive-700, #1e6b3d); border: 1px solid var(--positive-200, #c3e3ce); }
  .lg-banner svg { flex: 0 0 auto; margin-top: 1px; }
  .lg-trouble { margin-top: 4px; border-top: 1px solid var(--border-subtle); }
  .lg-trouble-panel { display: grid; gap: 9px; padding: 16px 2px 2px; font-family: ${NS}; font-size: 14px; color: var(--text-secondary); }
  .lg-trouble-row { display: flex; align-items: center; gap: 10px; }
  .lg-trouble-row a { color: var(--text-link); text-decoration: none; font-weight: 600; }
  .lg-trouble-row a:hover { text-decoration: underline; }
  .lg-tick { display: flex; align-items: flex-start; gap: 12px; font-family: ${NS}; font-size: 15.5px; color: var(--text-primary); }
  .lg-tick-mark { flex: 0 0 auto; width: 22px; height: 22px; border-radius: 50%; background: var(--brand-subtle); color: var(--brand); display: inline-flex; align-items: center; justify-content: center; margin-top: 1px; }
  .lg-eyebrow { font-family: ${NS}; font-weight: 700; font-size: 11.5px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--text-muted); }
  `;
  const el = document.createElement("style");
  el.setAttribute("data-ce", "login");
  el.textContent = css;
  document.head.appendChild(el);
}

/* ================================================================
   Trouble-signing-in disclosure — collapsed by default, expands
   in place with the regional support contacts.
================================================================ */
function TroubleSignIn({ open, onToggle }) {
  return (
    <div className="lg-trouble">
      <button type="button" className="lg-quietlink" aria-expanded={open} onClick={onToggle} style={{ padding: "14px 0 0" }}>
        Trouble signing in?
      </button>
      {open && (
        <div className="lg-trouble-panel">
          <div className="lg-trouble-row"><LIcon name="phone" size={16} /><span>Europe: <a href="tel:+442078235000">+44 (0)20 7823 5000</a></span></div>
          <div className="lg-trouble-row"><LIcon name="phone" size={16} /><span>North America: <a href="tel:+14164130428">+1 416 413 0428</a></span></div>
          <div className="lg-trouble-row"><LIcon name="phone" size={16} /><span>Asia: <a href="tel:+6565955190">+65 6595 5190</a></span></div>
          <div className="lg-trouble-row"><LIcon name="mail" size={16} /><span>Email: <a href="mailto:support@capitaleconomics.com">support@capitaleconomics.com</a></span></div>
        </div>
      )}
    </div>
  );
}

/* ================================================================
   Expired-trial panel — a successful sign-in with nothing to see.
   Replaces the form so the account holder is routed to the team
   rather than dropped at a dead end.
================================================================ */
function ExpiredPanel() {
  return (
    <div>
      <div style={{ width: 46, height: 46, borderRadius: "50%", background: "var(--brand-subtle)", color: "var(--brand)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 20 }}>
        <LIcon name="clock" size={24} />
      </div>
      <h2 style={{ fontFamily: SERIF, fontWeight: 600, fontSize: 26, lineHeight: 1.16, letterSpacing: "-0.015em", color: "var(--text-primary)", margin: 0 }}>
        Your free trial has ended
      </h2>
      <p style={{ fontFamily: NS, fontSize: 15.5, lineHeight: 1.55, color: "var(--text-secondary)", margin: "12px 0 26px" }}>
        Talk to our team about full access to Capital Economics research, data and forecasts.
      </p>
      <Button variant="primary" size="lg" block iconEnd={<LIcon name="arrow-right" size={18} />}>
        Talk to our team about full access
      </Button>
    </div>
  );
}

/* ================================================================
   Sign-in card — the reason the page exists. `state` drives the
   six designed states: default | error | failed | reset | expired
   | loading. When live (autofocus on), it validates on blur, lets
   Enter submit from either field, and enters the loading state on
   submit.
================================================================ */
function SignInCard({ state = "default", autofocus = false, elevated = false }) {
  const [email, setEmail] = React.useState(state === "error" ? "trader@" : "");
  const [pw, setPw] = React.useState("");
  const [show, setShow] = React.useState(false);
  const [emailErr, setEmailErr] = React.useState(state === "error" ? "Enter a valid business email address." : "");
  const [failed, setFailed] = React.useState(state === "failed");
  const [loading, setLoading] = React.useState(state === "loading");
  const [trouble, setTrouble] = React.useState(false);
  const [touched, setTouched] = React.useState(false);

  const validateEmail = () => {
    if (!email.trim()) { setEmailErr("Enter your business email address."); return false; }
    if (!EMAIL_RE.test(email.trim())) { setEmailErr("Enter a valid business email address."); return false; }
    setEmailErr(""); return true;
  };
  const onSubmit = (e) => {
    e.preventDefault();
    setTouched(true);
    setFailed(false);
    if (!validateEmail()) return;
    setLoading(true);
    setTimeout(() => setLoading(false), 1600);
  };

  const isExpired = state === "expired";

  return (
    <div style={{
      width: "100%", maxWidth: 460, background: "var(--surface-card)",
      border: "1px solid var(--border-default)", borderRadius: "var(--radius-lg)",
      boxShadow: elevated ? "0 14px 44px rgba(36,33,58,0.12)" : "0 6px 24px rgba(36,33,58,0.07)",
      padding: "36px 36px 30px",
    }}>
      {isExpired ? <ExpiredPanel /> : (
        <>
          <h1 style={{ fontFamily: SERIF, fontWeight: 600, fontSize: 30, lineHeight: 1.1, letterSpacing: "-0.02em", color: "var(--text-primary)", margin: 0 }}>
            Sign in
          </h1>
          <p style={{ fontFamily: NS, fontSize: 15.5, lineHeight: 1.5, color: "var(--text-secondary)", margin: "8px 0 26px" }}>
            Access your Capital Economics account.
          </p>

          {state === "reset" && (
            <div className="lg-banner lg-banner-ok" role="status">
              <LIcon name="check-circle" size={18} />
              <span><strong style={{ fontWeight: 700 }}>Password updated.</strong> Sign in with your new password.</span>
            </div>
          )}
          {failed && (
            <div className="lg-banner lg-banner-err" role="alert">
              <LIcon name="alert-circle" size={18} />
              <span>We could not sign you in. Check your email address and password and try again.</span>
            </div>
          )}

          <form onSubmit={onSubmit} noValidate>
            <Input
              label="Business email" type="email" name="username" required
              autoComplete="username" placeholder="you@firm.com"
              value={email} error={emailErr || undefined}
              autoFocus={autofocus}
              onChange={(e) => { setEmail(e.target.value); setTouched(true); }}
              onBlur={() => { if (touched) validateEmail(); }}
            />
            <div style={{ marginTop: 18 }}>
              <Input
                label="Password" type={show ? "text" : "password"} name="password" required
                autoComplete="current-password" value={pw}
                onChange={(e) => setPw(e.target.value)}
                suffix={
                  <button type="button" className="lg-pwtoggle" onClick={() => setShow((s) => !s)}
                    aria-label={show ? "Hide password" : "Show password"} aria-pressed={show}>
                    <LIcon name={show ? "eye-off" : "eye"} size={18} />
                  </button>
                }
              />
            </div>
            <div style={{ marginTop: 24 }}>
              <Button type="submit" variant="primary" size="lg" block disabled={loading}
                iconEnd={loading ? <LIcon name="loader" size={18} className="lg-spin" /> : null}>
                {loading ? "Signing in…" : "Sign in"}
              </Button>
            </div>
          </form>

          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, marginTop: 18 }}>
            <a href="#" className="lg-quietlink">Forgot your password?</a>
          </div>
          <TroubleSignIn open={trouble} onToggle={() => setTrouble((t) => !t)} />
        </>
      )}
    </div>
  );
}

/* ================================================================
   Trial block — the secondary path. Retired all "register" and
   "get access" wording; this leads to the trial and says so.
   `layout`: "band" (Variant A, full-width lighter band) or
   "column" (Variant B, low-contrast right column).
================================================================ */
const TRIAL_TICKS = [
  "Explore our insight now",
  "Start immediately",
  "Access up to 10 published articles",
  "Trusted by leading investors",
];
function TrialBlock({ layout = "band" }) {
  const column = layout === "column";
  return (
    <div style={{ maxWidth: column ? 400 : 560 }}>
      <div className="lg-eyebrow" style={{ marginBottom: 14 }}>Don't have an account?</div>
      <h2 style={{ fontFamily: SERIF, fontWeight: 600, fontSize: column ? 25 : 28, lineHeight: 1.16, letterSpacing: "-0.015em", color: "var(--text-primary)", margin: 0 }}>
        Experience the Capital Economics platform
      </h2>
      <p style={{ fontFamily: NS, fontSize: 15.5, lineHeight: 1.58, color: "var(--text-secondary)", margin: "14px 0 0" }}>
        Try the platform trusted by the world's leading financial institutions and governments. Explore how independent analysis, forecasts and economist expertise can support your team make smart decisions. No commitment or payment details required.
      </p>
      <ul style={{ listStyle: "none", padding: 0, margin: "22px 0 0", display: "grid", gap: 13 }}>
        {TRIAL_TICKS.map((t) => (
          <li key={t} className="lg-tick">
            <span className="lg-tick-mark"><LIcon name="check" size={13} stroke={2.6} /></span>
            <span>{t}</span>
          </li>
        ))}
      </ul>
      <div style={{ marginTop: 26 }}>
        <Button variant="secondary" size="lg" iconEnd={<LIcon name="arrow-right" size={18} />}>
          Start free trial
        </Button>
        <p style={{ fontFamily: NS, fontSize: 13.5, color: "var(--text-muted)", margin: "12px 0 0" }}>
          Free. 10 articles. No card required.
        </p>
      </div>
    </div>
  );
}

/* ================================================================
   Variant A — stacked single column. Sign-in card centred on a
   light neutral; the trial block sits in a visually lighter
   full-width band beneath, separated by a rule so it reads as a
   different question. Same order on desktop and mobile.
================================================================ */
function VariantA({ live = false }) {
  return (
    <div style={{ minHeight: "100%", display: "flex", flexDirection: "column", background: "var(--surface-page)" }}>
      <SiteHeader />
      <main style={{ flex: 1 }}>
        <section style={{ display: "flex", justifyContent: "center", padding: "72px 24px 76px" }}>
          <SignInCard state="default" autofocus={live} elevated />
        </section>
        <section style={{ background: "var(--surface-card)", borderTop: "1px solid var(--border-subtle)" }}>
          <div style={{ maxWidth: 620, margin: "0 auto", padding: "56px 24px 64px", display: "flex", justifyContent: "center" }}>
            <TrialBlock layout="band" />
          </div>
        </section>
      </main>
      <SiteFooter />
    </div>
  );
}

/* ================================================================
   Variant B — asymmetric two column (desktop). Sign-in ~60% left
   with visual dominance; trial ~40% right, lower contrast, no
   coloured fill competing with the primary CTA. A hairline divider
   keeps the two questions distinct. Collapses to Variant A's
   stacking order below 900px (handled by the .lg-vb-grid rule).
================================================================ */
function VariantB() {
  return (
    <div style={{ minHeight: "100%", display: "flex", flexDirection: "column", background: "var(--surface-page)" }}>
      <SiteHeader />
      <main style={{ flex: 1, display: "flex", alignItems: "center" }}>
        <div className="lg-vb-grid" style={{ width: "100%", maxWidth: 1100, margin: "0 auto", padding: "72px 32px", display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 64, alignItems: "center" }}>
          <div style={{ display: "flex", justifyContent: "center" }}>
            <SignInCard state="default" elevated />
          </div>
          <div style={{ borderLeft: "1px solid var(--border-subtle)", paddingLeft: 64 }} className="lg-vb-trial">
            <TrialBlock layout="column" />
          </div>
        </div>
      </main>
      <SiteFooter />
    </div>
  );
}

/* ---- responsive rule: Variant B collapses to stacked below 900px ---- */
(function injectVBResponsive() {
  if (typeof document === "undefined" || document.getElementById("lg-vb-css")) return;
  const el = document.createElement("style");
  el.id = "lg-vb-css";
  el.textContent = `@media (max-width: 900px){ .lg-vb-grid { grid-template-columns: 1fr !important; gap: 40px !important; } .lg-vb-trial { border-left: 0 !important; padding-left: 0 !important; border-top: 1px solid var(--border-subtle); padding-top: 40px !important; } }`;
  document.head.appendChild(el);
})();

/* ================================================================
   State artboard — a sign-in card on the light page surface so the
   six states can be reviewed in isolation.
================================================================ */
function StateFrame({ state }) {
  return (
    <div style={{ background: "var(--surface-page)", padding: "40px 32px", minHeight: "100%", display: "flex", justifyContent: "center", alignItems: "flex-start" }}>
      <SignInCard state={state} />
    </div>
  );
}

/* ================================================================
   Canvas assembly
================================================================ */
function annStyle() {
  return { fontFamily: NS, fontSize: 13.5, lineHeight: 1.5, color: "var(--text-secondary)" };
}

function App() {
  injectLoginCSS();
  return <VariantA live />;
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
