/* global React, ReactDOM, RibbonVisual, TimeOfDayVisual, FieldVisual,
   TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakColor, TweakToggle */
const { useState, useEffect, useRef, useCallback } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "variant": "ribbon",
  "darkVisual": true,
  "showTooltipHint": true,
  "headline": "Welcome back",
  "subline": "Sign in to your Method 8 workspace.",
  "accent": "#84caff",
  "formBg": "#eff8ff",
  "primaryBtn": "#354152",
  "headlineColor": "#0b4a6f",
  "theme": "light"
}/*EDITMODE-END*/;

function EggToast({ message, show }) {
  return (
    <div className={"egg-toast " + (show ? "show" : "")}>
      <span className="sparkle">✦</span>
      <span>{message}</span>
    </div>
  );
}

function GoogleIcon() {
  return (
    <svg viewBox="0 0 48 48" aria-hidden="true">
      <path fill="#FFC107" d="M43.611 20.083H42V20H24v8h11.303C33.974 32.659 29.41 36 24 36c-6.627 0-12-5.373-12-12s5.373-12 12-12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 12.955 4 4 12.955 4 24s8.955 20 20 20c11.045 0 20-8.955 20-20 0-1.341-.138-2.65-.389-3.917z"/>
      <path fill="#FF3D00" d="m6.306 14.691 6.571 4.819C14.655 15.108 18.961 12 24 12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 16.318 4 9.656 8.337 6.306 14.691z"/>
      <path fill="#4CAF50" d="M24 44c5.166 0 9.86-1.977 13.409-5.192l-6.19-5.238A11.91 11.91 0 0 1 24 36c-5.389 0-9.937-3.314-11.288-7.946l-6.522 5.025C9.535 39.554 16.227 44 24 44z"/>
      <path fill="#1976D2" d="M43.611 20.083H42V20H24v8h11.303a12.04 12.04 0 0 1-4.087 5.571l6.19 5.238C36.971 39.205 44 34 44 24c0-1.341-.138-2.65-.389-3.917z"/>
    </svg>
  );
}
function MicrosoftIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <rect x="2" y="2" width="9" height="9" fill="#F25022"/>
      <rect x="13" y="2" width="9" height="9" fill="#7FBA00"/>
      <rect x="2" y="13" width="9" height="9" fill="#00A4EF"/>
      <rect x="13" y="13" width="9" height="9" fill="#FFB900"/>
    </svg>
  );
}

function BrandLogo() {
  // Dark wordmark in light mode, light wordmark in dark mode.
  // The mark (3 ribbons) stays brand cyan in both. The rounded tile is
  // light in light theme, dark in dark theme.
  return (
    <svg width="158" height="40" viewBox="0 0 158 40" fill="none" xmlns="http://www.w3.org/2000/svg" aria-label="Method 8">
      <rect x="8" y="4" width="32" height="32" rx="6"
        fill="var(--logo-tile, #ffffff)"
        stroke="var(--logo-tile-stroke, #D0D5DD)" strokeWidth="0.2"/>
      <g fill="#36BFFA">
        <path d="M23.8912 21.7635C25.1808 23.556 27.3677 25.4431 29.6611 24.6927C31.8017 24.0771 33.037 21.6589 32.7614 19.5444C32.4455 16.0338 28.7679 14.0602 26.4985 17.3938C24.6919 19.7979 23.8128 23.0249 21.3342 24.9945C19.5879 26.4048 16.9102 25.8757 15.4516 24.2883C13.6671 22.1779 13.5082 19.0274 14.9989 16.7943C16.367 14.4887 19.6845 13.6639 21.7969 15.4282C22.8008 16.1565 23.5271 17.1725 24.1125 18.2428C23.3923 17.2771 22.5694 16.3798 21.5535 15.7984C18.2963 13.694 14.7414 17.0417 15.2444 20.4618C15.4295 22.5602 16.9484 24.5318 19.1433 24.3065C20.0345 24.1998 20.8453 23.5158 21.5032 22.6105C22.9094 20.7013 23.7625 18.3977 25.2593 16.4482C28.2569 12.1027 33.8236 14.5611 33.9946 19.4278C34.2159 22.0592 32.5119 24.8879 29.8583 25.4451C27.2349 26.0628 24.9997 23.9162 23.8912 21.7635Z"/>
        <path d="M23.6883 22.1353C25.4164 24.5998 28.1364 27.2836 31.3775 26.4386C34.3711 25.7224 36.1918 22.4432 35.884 19.5159C35.6566 16.5485 33.6629 13.7862 30.5064 14.0176C27.559 14.4502 26.1145 17.9749 24.7042 20.383C23.0787 23.1714 21.3344 27.0885 17.6367 27.4888C13.6754 27.7202 10.9976 24.3242 10.885 20.5802C10.4363 15.0617 16.4598 10.2374 21.2379 14.1001C22.5677 15.0819 23.5052 16.458 24.32 17.8682C22.9379 15.9409 21.2258 14.0659 18.8679 13.5167C16.6207 13.0157 14.2548 14.2671 13.1423 16.2125C10.9795 19.522 12.243 25.2718 16.498 25.9578C21.1695 26.6881 23.2557 18.3953 25.9093 15.3977C27.5107 13.0861 30.3454 11.6919 33.0714 13.0097C35.6808 13.9432 36.9905 16.812 37.1213 19.4254C37.3667 22.8797 35.0531 26.5674 31.5505 27.1991C28.0459 27.8771 25.2132 24.9579 23.6883 22.1374V22.1353Z"/>
        <path d="M24.1033 21.3734C25.0126 22.4557 26.5175 23.5763 27.9458 22.9104C29.8873 22.1499 30.2192 19.1825 28.8089 17.8406C25.9501 15.7342 24.8979 20.8644 23.3971 22.4879C21.3833 25.5298 17.3294 24.0109 17.1363 20.5968C16.7158 17.8225 19.812 14.9677 22.3308 16.7663C23.035 17.2169 23.4957 17.913 23.9041 18.6071C22.9947 17.5267 21.4899 16.4041 20.0615 17.0721C18.79 17.5851 18.1201 19.1322 18.3695 20.4358C18.5607 21.7254 19.47 22.7917 20.7777 22.6328C21.2485 22.5382 21.7353 22.1399 22.1478 21.5544C23.3146 19.951 23.9343 17.8285 25.5679 16.4927C27.807 14.7122 30.8147 16.8065 30.865 19.3837C31.1447 23.7795 26.1513 25.5358 24.1012 21.3734H24.1033Z"/>
      </g>
      <g fill="var(--logo-text, #344054)">
        <path d="M48.1472 12.1367H51.5626L56.3306 23.8379L61.0987 12.1367H64.4932V27.8746H61.4866V17.6387L57.4683 27.8746H55.1904L51.1511 17.6387V27.8746H48.1445V12.1367H48.1472Z"/>
        <path d="M72.2911 28.0127C68.8677 28.0127 66.3828 25.6327 66.3828 21.9341C66.3828 18.2355 68.8048 15.8555 72.2911 15.8555C75.7773 15.8555 78.0945 18.1726 78.0945 21.6798C78.0945 22.0625 78.0735 22.4452 78.0106 22.8279H69.4025C69.5519 24.5711 70.7419 25.5488 72.2308 25.5488C73.5073 25.5488 74.2072 24.9118 74.5899 24.1255H77.7983C77.1613 26.2932 75.2059 28.0154 72.2937 28.0154L72.2911 28.0127ZM69.4208 20.8279H75.0119C74.97 19.2762 73.7354 18.2985 72.2072 18.2985C70.7839 18.2985 69.6567 19.2133 69.4234 20.8279H69.4208Z"/>
        <path d="M80.5709 18.4485H79.082V15.8561H80.5709V12.1523H83.7504V15.8561H86.5473V18.4485H83.7504V24.0187C83.7504 24.8522 84.0886 25.2139 85.0794 25.2139H86.5447V27.8745H84.5604C82.1698 27.8745 80.5709 26.8601 80.5709 23.9977V18.4485Z"/>
        <path d="M88.5605 12.1035H91.7165V17.5924C92.5291 16.5334 93.9262 15.8571 95.5933 15.8571C98.4111 15.8571 100.01 17.7523 100.01 21.2018V27.8755H96.8541V21.6291C96.8541 19.6212 96.2041 18.5413 94.5343 18.5413C92.8646 18.5413 91.7165 19.6238 91.7165 21.6291V27.8755H88.5605V12.1061V12.1035Z"/>
        <path d="M107.825 28.0758C104.402 28.0758 101.814 25.68 101.814 21.9578C101.814 18.2357 104.488 15.8398 107.911 15.8398C111.335 15.8398 114.008 18.2147 114.008 21.9578C114.008 25.7009 111.269 28.0758 107.828 28.0758H107.825ZM107.825 25.4676C109.408 25.4676 110.926 24.3117 110.926 21.9604C110.926 19.6092 109.45 18.4532 107.867 18.4532C106.284 18.4532 104.85 19.5856 104.85 21.9604C104.85 24.3353 106.218 25.4676 107.822 25.4676H107.825Z"/>
        <path d="M120.942 15.1626C122.588 15.1626 124.166 15.928 125.023 17.1023V12.0879H128.223V27.8572H125.023V26.0093C124.278 27.16 122.881 28.0617 120.921 28.0617C117.741 28.0617 115.217 25.4693 115.217 21.5689C115.217 17.6685 117.741 15.1652 120.944 15.1652L120.942 15.1626ZM121.731 17.9359C120.04 17.9359 118.438 19.1993 118.438 21.5663C118.438 23.9332 120.04 25.2858 121.731 25.2858C123.421 25.2858 125.044 23.9778 125.044 21.6108C125.044 19.2439 123.466 17.9359 121.731 17.9359Z"/>
        <path d="M130.613 16.2092C130.613 13.9969 132.298 12.0781 135.798 12.0781C139.297 12.0781 140.983 14.0178 140.983 16.2092C140.983 17.8317 140.097 18.9929 138.896 19.6037C140.414 20.2564 141.363 21.5853 141.363 23.3783C141.363 26.3088 138.959 28.0781 135.798 28.0781C132.637 28.0781 130.254 26.3062 130.254 23.3783C130.254 21.5644 131.203 20.238 132.72 19.6037C131.454 18.951 130.613 17.8763 130.613 16.2092ZM133.101 23.2498C133.101 24.6207 134.112 25.6325 135.798 25.6325C137.483 25.6325 138.474 24.5998 138.474 23.2498C138.474 21.7321 137.378 20.8881 135.798 20.8881C134.217 20.8881 133.101 21.6902 133.101 23.2498ZM138.118 16.6286C138.118 15.2367 137.211 14.4582 135.798 14.4582C134.385 14.4582 133.499 15.2157 133.499 16.6496C133.499 17.9156 134.469 18.7361 135.798 18.7361C137.127 18.7361 138.118 17.892 138.118 16.6286Z"/>
      </g>
    </svg>
  );
}


function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPw, setShowPw] = useState(false);
  const [remember, setRemember] = useState(true);
  const [emailErr, setEmailErr] = useState("");
  const [pwErr, setPwErr] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [eggMessage, setEggMessage] = useState(null);
  const [eggShow, setEggShow] = useState(false);

  const showEgg = useCallback((msg) => {
    setEggMessage(msg);
    setEggShow(true);
    clearTimeout(showEgg._t);
    showEgg._t = setTimeout(() => setEggShow(false), 2400);
  }, []);

  const validate = () => {
    let ok = true;
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setEmailErr("Enter a valid work email"); ok = false;
    } else setEmailErr("");
    if (!password || password.length < 6) {
      setPwErr("Password must be at least 6 characters"); ok = false;
    } else setPwErr("");
    return ok;
  };

  const onSubmit = (e) => {
    e.preventDefault();
    if (!validate()) return;
    setSubmitting(true);
    setTimeout(() => { setSubmitting(false); showEgg("Signed in (demo)"); }, 1400);
  };

  // Reduce-motion respect
  const reduceMotion = typeof window !== "undefined" && window.matchMedia &&
    window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  // Apply form-side color tweaks via CSS variables
  useEffect(() => {
    const r = document.documentElement;
    const dark = r.getAttribute('data-theme') === 'dark';
    r.style.setProperty('--form-bg', dark
      ? 'linear-gradient(180deg, #0e1626 0%, #0a111c 60%)'
      : `linear-gradient(180deg, ${t.formBg} 0%, #ffffff 60%)`);
    r.style.setProperty('--primary-btn', dark ? '#E6F4FF' : t.primaryBtn);
    r.style.setProperty('--primary-btn-hover', dark ? '#ffffff' : t.primaryBtn);
    r.style.setProperty('--link', dark ? '#7CD4FD' : t.primaryBtn);
    document.querySelectorAll('h1').forEach((h) => { h.style.color = dark ? '' : t.headlineColor; });
  }, [t.formBg, t.primaryBtn, t.headlineColor, t.theme]);

  // Theme: light | dark | system
  useEffect(() => {
    const apply = () => {
      const sysDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
      const dark = t.theme === 'dark' || (t.theme === 'system' && sysDark);
      document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
      // Re-apply or override the headline color so dark mode wins over the tweak effect
      document.querySelectorAll('h1').forEach((h) => {
        h.style.color = dark ? '' : t.headlineColor;
      });
    };
    apply();
    if (t.theme === 'system' && window.matchMedia) {
      const mq = window.matchMedia('(prefers-color-scheme: dark)');
      mq.addEventListener('change', apply);
      return () => mq.removeEventListener('change', apply);
    }
  }, [t.theme, t.headlineColor]);

  const Visual = {
    ribbon: RibbonVisual,
    timeofday: TimeOfDayVisual,
    field: FieldVisual,
  }[t.variant] || RibbonVisual;

  return (
    <>
      <div className="stage">
        <section className="form-side">
          <div className="top">
            <div className="brand"><BrandLogo/></div>
          </div>

          <form className="form-card" onSubmit={onSubmit} noValidate>
            <h1>{t.headline}</h1>
            <p className="sub">{t.subline}</p>

            <div className="sso-row" style={{gridTemplateColumns:'1fr'}}>
              <button type="button" className="sso-btn" onClick={() => showEgg("Microsoft SSO (demo)")}>
                <MicrosoftIcon/> Continue with Microsoft
              </button>
            </div>

            <div className="divider">or sign in with email</div>

            <div className="field">
              <label htmlFor="email">Work email</label>
              <div className="input-wrap">
                <input id="email" type="email" value={email}
                  className={emailErr ? "invalid" : ""}
                  onChange={(e) => { setEmail(e.target.value); if (emailErr) setEmailErr(""); }}
                  placeholder="you@company.com" autoComplete="email"/>
              </div>
              <div className="err">{emailErr}</div>
            </div>

            <div className="field">
              <label htmlFor="pw">Password</label>
              <div className="input-wrap">
                <input id="pw" type={showPw ? "text" : "password"} value={password}
                  className={pwErr ? "invalid" : ""}
                  onChange={(e) => { setPassword(e.target.value); if (pwErr) setPwErr(""); }}
                  placeholder="••••••••" autoComplete="current-password"/>
                <button type="button" className="reveal" aria-label={showPw ? "Hide password" : "Show password"}
                        onClick={() => setShowPw(!showPw)}>
                  {showPw ? (
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M17.94 17.94A10.94 10.94 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/><path d="M9.9 4.24A10.94 10.94 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
                  ) : (
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  )}
                </button>
              </div>
              <div className="err">{pwErr}</div>
            </div>

            <div className="row-between">
              <label className="check">
                <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)}/>
                <span className="box"></span>
                Remember for 30 days
              </label>
              <a href="#">Forgot password?</a>
            </div>

            <button className="submit" type="submit" disabled={submitting}>
              {submitting ? <><span className="spin"></span>Signing in…</> : "Sign in"}
            </button>

            <div className="footer-msg">
              Don't have an account? <a href="#">Request access</a>
            </div>
          </form>

          <div className="legal">
            <span>© 2025 Onwards Analytics</span>
            <a href="#">Privacy</a>
            <a href="#">Terms</a>
            <a href="#">Status</a>
          </div>
        </section>

        <aside className="visual">
          <Visual onEgg={showEgg} reduceMotion={reduceMotion} accent={t.accent} email={email}/>
          <div className="corner-tag"><span className="live-dot"></span>Method 8 · v3.4</div>

          {t.variant === "ribbon" && (
            <div className="quote">
              <div className="mark">"</div>
              <h3>We replaced four spreadsheets and a shared inbox with one assessment per programme. Audit week was actually calm.</h3>
            </div>
          )}
          {t.variant === "timeofday" && (
            <div className="quote">
              <h3 style={{fontSize: 18, lineHeight: '26px', opacity: 0.85}}>
                <span style={{opacity: 0.6, display:'block', fontSize: 12, fontWeight: 600, letterSpacing: '0.5px', textTransform: 'uppercase', marginBottom: 8}}>Right now</span>
                3 assessments are due this week. 12 colleagues are signed in.
              </h3>
            </div>
          )}
          {t.variant === "field" && (
            <div className="quote">
              <h3 style={{fontSize: 16, lineHeight: '24px', opacity: 0.7, fontWeight: 400, fontStyle: 'italic'}}>
                <span style={{opacity: 0.6, display:'block', fontSize: 11, fontWeight: 600, letterSpacing: '0.5px', textTransform: 'uppercase', marginBottom: 8, fontStyle: 'normal'}}>Try it</span>
                Triple-click the mark.
              </h3>
            </div>
          )}
        </aside>
      </div>

      <EggToast message={eggMessage} show={eggShow}/>

      <TweaksPanel title="Tweaks">
        <TweakSection title="Direction">
          <TweakRadio label="Variant"
            value={t.variant}
            onChange={(v) => setTweak("variant", v)}
            options={[
              { value: "ribbon", label: "A · Ribbon" },
              { value: "timeofday", label: "B · Time" },
              { value: "field", label: "C · Field" },
            ]}/>
          <TweakToggle label="Show hint copy" value={t.showTooltipHint} onChange={(v) => setTweak("showTooltipHint", v)}/>
        </TweakSection>
        <TweakSection title="Theme">
          <TweakRadio label="Mode"
            value={t.theme}
            onChange={(v) => setTweak("theme", v)}
            options={[
              { value: "light", label: "Light" },
              { value: "dark", label: "Dark" },
              { value: "system", label: "Auto" },
            ]}/>
        </TweakSection>
        <TweakSection title="Copy">
          <input value={t.headline} onChange={(e) => setTweak("headline", e.target.value)}
            style={{width:'100%',padding:'8px 10px',border:'1px solid #d0d5dd',borderRadius:6,font:'inherit',fontSize:13}}/>
          <input value={t.subline} onChange={(e) => setTweak("subline", e.target.value)}
            style={{width:'100%',padding:'8px 10px',border:'1px solid #d0d5dd',borderRadius:6,font:'inherit',fontSize:13,marginTop:8}}/>
        </TweakSection>
        <TweakSection title="Accent">
          <TweakColor label="Visual accent" value={t.accent} onChange={(v) => setTweak("accent", v)}
            options={["#84caff", "#7CD4FD", "#a4bcfd", "#fec84b", "#75e0a7"]}/>
        </TweakSection>
        <TweakSection title="Form colors">
          <TweakColor label="Form background" value={t.formBg} onChange={(v) => setTweak("formBg", v)}
            options={["#eff8ff", "#ffffff", "#fafaf9", "#fef6ee", "#f5f3ff"]}/>
          <TweakColor label="Primary button" value={t.primaryBtn} onChange={(v) => setTweak("primaryBtn", v)}
            options={["#1570ef", "#354152", "#0086c9", "#079455", "#7c3aed"]}/>
          <TweakColor label="Headline color" value={t.headlineColor} onChange={(v) => setTweak("headlineColor", v)}
            options={["#0b4a6f", "#101828", "#1570ef", "#7c2d12", "#1c1917"]}/>
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

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