/* global React, window, Icon, Mascot, useT, useEyad, SUBJECTS */
// Eyad Academy — Auth screens (Login + Register) and floating WhatsApp button

const { useState, useEffect } = React;

// Replace with the real number when you have it
const WHATSAPP_NUMBER = "966500000000";
const WHATSAPP_TEXT = {
  ar: "السلام عليكم، أرغب في الاستفسار عن أكاديمية إياد.",
  en: "Hi! I'd like to learn more about Eyad Academy.",
};

// ============================================================
// FLOATING WHATSAPP BUTTON
// ============================================================
function WhatsAppButton() {
  const t = useT();
  const { lang } = useEyad();
  const [open, setOpen] = useState(false);

  const link = `https://wa.me/${WHATSAPP_NUMBER}?text=${encodeURIComponent(WHATSAPP_TEXT[lang] || WHATSAPP_TEXT.en)}`;

  return (
    <div className="wa-fab">
      {open && (
        <div className="wa-card">
          <button className="wa-card-close" onClick={() => setOpen(false)} aria-label="close">
            <Icon name="close" size={14}/>
          </button>
          <div className="wa-card-head">
            <div className="wa-avatar">
              <WhatsAppGlyph/>
            </div>
            <div>
              <div className="wa-card-name">{t.nav.brand}</div>
              <div className="wa-card-status"><span/> {lang === "ar" ? "متاحون الآن" : "Online now"}</div>
            </div>
          </div>
          <div className="wa-bubble">
            {lang === "ar"
              ? "أهلًا 👋 كيف نقدر نخدمك؟ نجاوبك خلال دقائق."
              : "Hi 👋 How can we help? We usually reply within minutes."}
          </div>
          <a href={link} target="_blank" rel="noopener" className="wa-cta">
            <WhatsAppGlyph small/>
            <span>{t.auth.whatsapp}</span>
          </a>
        </div>
      )}
      <button className="wa-btn" onClick={() => setOpen(o => !o)} aria-label="WhatsApp">
        {open
          ? <Icon name="close" size={22}/>
          : <WhatsAppGlyph/>}
        {!open && <span className="wa-pulse"/>}
      </button>
    </div>
  );
}

function WhatsAppGlyph({ small = false }) {
  const size = small ? 18 : 28;
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="white">
      <path d="M16 3C8.8 3 3 8.8 3 16c0 2.3.6 4.5 1.7 6.4L3 29l6.8-1.8C11.7 28.4 13.8 29 16 29c7.2 0 13-5.8 13-13S23.2 3 16 3zm0 23.7c-1.9 0-3.8-.5-5.4-1.5l-.4-.2-4 1.1 1.1-3.9-.3-.4c-1.1-1.7-1.6-3.6-1.6-5.6 0-5.9 4.8-10.7 10.7-10.7S26.7 10.3 26.7 16 21.9 26.7 16 26.7zm6-7.9c-.3-.2-1.9-.9-2.2-1s-.5-.2-.7.2c-.2.3-.8 1-1 1.2-.2.2-.4.2-.7.1-.3-.2-1.4-.5-2.6-1.6-1-.9-1.6-2-1.8-2.3-.2-.3 0-.5.1-.6.1-.1.3-.4.4-.5.1-.2.2-.3.3-.5.1-.2.1-.4 0-.5-.1-.2-.7-1.7-1-2.3-.3-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4s-1.1 1.1-1.1 2.6c0 1.5 1.1 3 1.3 3.2.2.2 2.2 3.3 5.3 4.6.7.3 1.3.5 1.8.6.7.2 1.4.2 2 .1.6-.1 1.9-.8 2.1-1.5.3-.7.3-1.4.2-1.5-.1-.2-.3-.3-.6-.4z"/>
    </svg>
  );
}

// ============================================================
// AUTH SHELL — wraps login/register with brand panel + form panel
// ============================================================
function AuthShell({ children, panelKey = "default", onClose }) {
  const t = useT();
  const { lang } = useEyad();
  useEffect(() => {
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", onKey); };
  }, [onClose]);

  return (
    <div className="auth-root">
      <aside className={`auth-side auth-side-${panelKey}`}>
        <div className="auth-side-blob auth-side-blob-1"/>
        <div className="auth-side-blob auth-side-blob-2"/>
        <div className="auth-side-stars">
          {[
            [12, 18, 1.3], [85, 12, 1], [22, 78, 1.5], [78, 82, 1.2],
            [50, 30, 0.9], [40, 88, 1.1], [88, 50, 1], [10, 55, 1.2],
          ].map(([x, y, s], i) => (
            <span key={i} className="auth-star" style={{ top: `${y}%`, left: `${x}%`, transform: `scale(${s})`, animationDelay: `${i * 0.4}s` }}/>
          ))}
        </div>
        <button className="auth-back" onClick={onClose}>
          <Icon name="chevron" size={16}/>
          <span>{t.auth.back}</span>
        </button>
        <div className="auth-side-mascot">
          <img src="assets/mascot.png" alt="Eyad"/>
        </div>
        <div className="auth-side-copy">
          <div className="auth-side-kicker">
            <span className="dot"/>
            {panelKey === "register" ? t.auth.register.kicker : t.auth.login.kicker}
          </div>
          <h2>
            {panelKey === "register" ? t.auth.register.title : t.auth.login.side.title}
          </h2>
          <p>
            {panelKey === "register" ? t.auth.register.subtitle : t.auth.login.side.body}
          </p>
        </div>
      </aside>
      <main className="auth-main">
        {children}
      </main>
    </div>
  );
}

// ============================================================
// LOGIN SCREEN
// ============================================================
function LoginScreen({ onClose, onSignedIn, onGoRegister }) {
  const t = useT();
  const [form, setForm] = useState({ email: "", password: "" });
  const [show, setShow] = useState(false);
  const [remember, setRemember] = useState(true);
  const [errs, setErrs] = useState({});
  const [submitted, setSubmitted] = useState(false);

  const submit = (e) => {
    e.preventDefault();
    const n = {};
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) n.email = t.auth.login.errors.email;
    if (form.password.length < 6) n.password = t.auth.login.errors.password;
    setErrs(n);
    if (Object.keys(n).length === 0) setSubmitted(true);
  };

  return (
    <AuthShell panelKey="login" onClose={onClose}>
      <div className="auth-form">
        <div className="auth-brand">
          <span className="brand-mark"><Icon name="spark" size={20}/></span>
          <span>{t.nav.brand}</span>
        </div>

        {submitted ? (
          <div className="auth-success">
            <div className="auth-check"><Icon name="check" size={32}/></div>
            <h2>{t.auth.login.success.title}</h2>
            <p>{t.auth.login.success.body}</p>
            <button className="btn btn-primary" onClick={onSignedIn}>
              {t.auth.login.success.btn}
              <Icon name="arrow" size={16}/>
            </button>
          </div>
        ) : (
          <>
            <div className="auth-head">
              <h1>{t.auth.login.title}</h1>
              <p>{t.auth.login.subtitle}</p>
            </div>

            <form onSubmit={submit} className="auth-fields">
              <label className="af-label">{t.auth.login.labels.email}</label>
              <input type="email" className="af-input" placeholder={t.auth.login.ph.email} dir="ltr"
                value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })}/>
              {errs.email && <div className="af-err">{errs.email}</div>}

              <div className="af-row-between">
                <label className="af-label">{t.auth.login.labels.password}</label>
                <a className="af-link" href="#">{t.auth.login.forgot}</a>
              </div>
              <div className="af-input-wrap">
                <input type={show ? "text" : "password"} className="af-input" placeholder={t.auth.login.ph.password} dir="ltr"
                  value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })}/>
                <button type="button" className="af-toggle" onClick={() => setShow(s => !s)}>
                  <EyeIcon open={!show}/>
                </button>
              </div>
              {errs.password && <div className="af-err">{errs.password}</div>}

              <label className="af-check">
                <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)}/>
                <span className="af-check-box"><Icon name="check" size={12}/></span>
                <span>{t.auth.login.remember}</span>
              </label>

              <button type="submit" className="btn btn-primary auth-submit">
                {t.auth.login.submit}
                <Icon name="arrow" size={16}/>
              </button>
            </form>

            <div className="auth-or"><span>{t.auth.login.or}</span></div>
            <div className="auth-socials">
              <button className="auth-social"><GoogleIcon/> {t.auth.login.google}</button>
              <button className="auth-social"><AppleIcon/> {t.auth.login.apple}</button>
            </div>

            <div className="auth-foot">
              {t.auth.login.noaccount}{" "}
              <button className="af-link" onClick={onGoRegister}>{t.auth.login.create}</button>
            </div>
          </>
        )}
      </div>
    </AuthShell>
  );
}

function EyeIcon({ open }) {
  return open ? (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z"/>
      <circle cx="12" cy="12" r="3"/>
    </svg>
  ) : (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 3l18 18"/>
      <path d="M10.7 5.1A10 10 0 0 1 22 12s-1.3 2.4-3.6 4.4"/>
      <path d="M6.2 6.2C3.3 8.2 2 12 2 12s4 7 10 7c1.7 0 3.3-.5 4.6-1.2"/>
      <path d="M9.9 9.9a3 3 0 0 0 4.2 4.2"/>
    </svg>
  );
}
function GoogleIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 48 48">
      <path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3c-1.6 4.7-6 8-11.3 8-6.6 0-12-5.4-12-12s5.4-12 12-12c3 0 5.8 1.1 7.9 3l5.6-5.6C33.7 6.5 29 4.5 24 4.5 13.2 4.5 4.5 13.2 4.5 24S13.2 43.5 24 43.5c10.8 0 19.5-8.7 19.5-19.5 0-1.3-.1-2.3-.4-3.5z"/>
      <path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.7 19 13 24 13c3 0 5.8 1.1 7.9 3l5.6-5.6C33.7 7 29 5 24 5 16.3 5 9.7 9.4 6.3 14.7z"/>
      <path fill="#4CAF50" d="M24 43.5c4.8 0 9.2-1.8 12.5-4.8l-5.8-4.9c-1.9 1.3-4.3 2.2-6.8 2.2-5.2 0-9.6-3.3-11.2-8L6 32.6c3.3 6.5 10 10.9 18 10.9z"/>
      <path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.3-2.3 4.3-4.2 5.7l5.8 4.9c-.4.4 6.6-4.8 6.6-14.6 0-1.3-.1-2.3-.4-3.5z"/>
    </svg>
  );
}
function AppleIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
      <path d="M17.05 12.5c0-2.4 2-3.6 2.05-3.6-1.1-1.6-2.85-1.85-3.45-1.85-1.45-.15-2.85.85-3.6.85-.75 0-1.9-.85-3.1-.8-1.6.05-3.05.95-3.85 2.4-1.65 2.85-.4 7.05 1.2 9.4.8 1.15 1.7 2.4 2.95 2.35 1.2-.05 1.6-.75 3-.75 1.4 0 1.8.75 3.05.75 1.25-.05 2.05-1.15 2.85-2.3.9-1.35 1.25-2.65 1.3-2.7-.05-.05-2.45-.95-2.4-3.75zm-2.6-6.95c.65-.85 1.1-1.95 1-3.05-.95.05-2.15.65-2.85 1.45-.6.75-1.2 1.95-1.05 3 1.05.1 2.2-.55 2.9-1.4z"/>
    </svg>
  );
}

// ============================================================
// REGISTER SCREEN — 3 steps + done state
// ============================================================
function RegisterScreen({ onClose, onSignedIn, onGoLogin }) {
  const t = useT();
  const [step, setStep] = useState(1);
  const [form, setForm] = useState({
    name: "", email: "", phone: "", password: "", agree: false,
    studentName: "", age: "", grade: "g3", gender: "f", subjects: [],
    plan: "premium",
  });
  const [errs, setErrs] = useState({});

  const setF = (k, v) => setForm(prev => ({ ...prev, [k]: v }));
  const toggleSubject = (id) => {
    setF("subjects", form.subjects.includes(id)
      ? form.subjects.filter(s => s !== id)
      : [...form.subjects, id]);
  };

  const validateStep = (s) => {
    const n = {};
    if (s === 1) {
      if (!form.name.trim()) n.name = t.auth.register.errors.name;
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) n.email = t.auth.register.errors.email;
      if (!/^[+]?[\d\s\-()]{8,}$/.test(form.phone)) n.phone = t.auth.register.errors.phone;
      if (form.password.length < 8) n.password = t.auth.register.errors.password;
      if (!form.agree) n.agree = t.auth.register.errors.agree;
    }
    if (s === 2) {
      if (!form.studentName.trim()) n.studentName = t.auth.register.errors.studentName;
      if (!form.age || Number(form.age) < 4 || Number(form.age) > 17) n.age = t.auth.register.errors.age;
      if (form.subjects.length === 0) n.subjects = t.auth.register.errors.subjects;
    }
    if (s === 3) {
      if (!form.plan) n.plan = t.auth.register.errors.plan;
    }
    setErrs(n);
    return Object.keys(n).length === 0;
  };

  const next = () => { if (validateStep(step)) setStep(s => Math.min(4, s + 1)); };
  const prev = () => { setErrs({}); setStep(s => Math.max(1, s - 1)); };

  return (
    <AuthShell panelKey="register" onClose={onClose}>
      <div className="auth-form">
        <div className="auth-brand">
          <span className="brand-mark"><Icon name="spark" size={20}/></span>
          <span>{t.nav.brand}</span>
        </div>

        {step < 4 && (
          <div className="auth-stepper">
            {t.auth.register.steps.map((label, i) => {
              const n = i + 1;
              const state = n < step ? "done" : n === step ? "active" : "todo";
              return (
                <div className={`step-pill step-${state}`} key={i}>
                  <span className="step-n">{state === "done" ? <Icon name="check" size={12}/> : n}</span>
                  <span className="step-label">{label}</span>
                </div>
              );
            })}
          </div>
        )}

        {step === 1 && (
          <RegisterStep1 form={form} setF={setF} errs={errs} t={t}/>
        )}
        {step === 2 && (
          <RegisterStep2 form={form} setF={setF} errs={errs} t={t} toggleSubject={toggleSubject}/>
        )}
        {step === 3 && (
          <RegisterStep3 form={form} setF={setF} errs={errs} t={t}/>
        )}
        {step === 4 && (
          <RegisterDone form={form} onSignedIn={onSignedIn} onClose={onClose} t={t}/>
        )}

        {step < 4 && (
          <div className="auth-step-nav">
            <button className="btn btn-ghost" onClick={prev} disabled={step === 1} style={{ visibility: step === 1 ? "hidden" : "visible" }}>
              <Icon name="chevron" size={14}/>
              {t.auth.register.prev}
            </button>
            <button className="btn btn-primary" onClick={step === 3 ? () => { if (validateStep(3)) setStep(4); } : next}>
              {step === 3 ? t.auth.register.finish : t.auth.register.next}
              <Icon name="arrow" size={16}/>
            </button>
          </div>
        )}

        {step < 4 && (
          <div className="auth-foot">
            {t.auth.register.haveAccount}{" "}
            <button className="af-link" onClick={onGoLogin}>{t.auth.register.signin}</button>
          </div>
        )}
      </div>
    </AuthShell>
  );
}

function RegisterStep1({ form, setF, errs, t }) {
  const s = t.auth.register.s1;
  return (
    <>
      <div className="auth-head">
        <h1>{s.h}</h1>
        <p>{s.d}</p>
      </div>
      <div className="auth-fields">
        <label className="af-label">{s.name}</label>
        <input className="af-input" placeholder={s.namePh}
          value={form.name} onChange={(e) => setF("name", e.target.value)}/>
        {errs.name && <div className="af-err">{errs.name}</div>}

        <label className="af-label">{s.email}</label>
        <input type="email" className="af-input" placeholder={s.emailPh} dir="ltr"
          value={form.email} onChange={(e) => setF("email", e.target.value)}/>
        {errs.email && <div className="af-err">{errs.email}</div>}

        <div className="af-grid-2">
          <div>
            <label className="af-label">{s.phone}</label>
            <input className="af-input" placeholder={s.phonePh} dir="ltr"
              value={form.phone} onChange={(e) => setF("phone", e.target.value)}/>
            {errs.phone && <div className="af-err">{errs.phone}</div>}
          </div>
          <div>
            <label className="af-label">{s.password}</label>
            <input type="password" className="af-input" placeholder={s.passwordPh} dir="ltr"
              value={form.password} onChange={(e) => setF("password", e.target.value)}/>
            {errs.password && <div className="af-err">{errs.password}</div>}
          </div>
        </div>

        <label className="af-check">
          <input type="checkbox" checked={form.agree} onChange={(e) => setF("agree", e.target.checked)}/>
          <span className="af-check-box"><Icon name="check" size={12}/></span>
          <span>
            {s.agree} <a className="af-link" href="#">{s.terms}</a> {s.and} <a className="af-link" href="#">{s.privacy}</a>
          </span>
        </label>
        {errs.agree && <div className="af-err">{errs.agree}</div>}
      </div>
    </>
  );
}

function RegisterStep2({ form, setF, errs, t, toggleSubject }) {
  const s = t.auth.register.s2;
  return (
    <>
      <div className="auth-head">
        <h1>{s.h}</h1>
        <p>{s.d}</p>
      </div>
      <div className="auth-fields">
        <div className="af-grid-2">
          <div>
            <label className="af-label">{s.name}</label>
            <input className="af-input" placeholder={s.namePh}
              value={form.studentName} onChange={(e) => setF("studentName", e.target.value)}/>
            {errs.studentName && <div className="af-err">{errs.studentName}</div>}
          </div>
          <div>
            <label className="af-label">{s.age}</label>
            <input type="number" min="4" max="17" className="af-input" placeholder={s.agePh}
              value={form.age} onChange={(e) => setF("age", e.target.value)}/>
            {errs.age && <div className="af-err">{errs.age}</div>}
          </div>
        </div>

        <div className="af-grid-2">
          <div>
            <label className="af-label">{s.grade}</label>
            <select className="af-input" value={form.grade} onChange={(e) => setF("grade", e.target.value)}>
              {Object.entries(s.gradeOpts).map(([k, v]) => (
                <option key={k} value={k}>{v}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="af-label">{s.gender}</label>
            <div className="af-segmented">
              {Object.entries(s.genderOpts).map(([k, v]) => (
                <button key={k} type="button"
                  className={`af-seg ${form.gender === k ? "active" : ""}`}
                  onClick={() => setF("gender", k)}>
                  {v}
                </button>
              ))}
            </div>
          </div>
        </div>

        <label className="af-label" style={{ marginTop: 8 }}>{s.subjects}</label>
        <div className="af-hint">{s.subjectsHint}</div>
        <div className="af-subj-grid">
          {SUBJECTS.map((sub) => {
            const on = form.subjects.includes(sub.id);
            return (
              <button key={sub.id} type="button"
                className={`af-subj ${on ? "on" : ""}`}
                onClick={() => toggleSubject(sub.id)}>
                <div className="af-subj-glyph" style={{ background: sub.glyph }}>
                  <Icon name={sub.icon} size={22}/>
                </div>
                <div className="af-subj-text">
                  <div className="af-subj-name">{t.subjects.items[sub.id].name}</div>
                  <div className="af-subj-en">{sub.en}</div>
                </div>
                <div className="af-subj-check"><Icon name="check" size={14}/></div>
              </button>
            );
          })}
        </div>
        {errs.subjects && <div className="af-err">{errs.subjects}</div>}
      </div>
    </>
  );
}

function RegisterStep3({ form, setF, errs, t }) {
  const s = t.auth.register.s3;
  return (
    <>
      <div className="auth-head">
        <h1>{s.h}</h1>
        <p>{s.d}</p>
      </div>
      <div className="af-plans">
        {s.plans.map((p) => {
          const on = form.plan === p.id;
          return (
            <button key={p.id} type="button"
              className={`af-plan ${on ? "on" : ""} ${p.popular ? "popular" : ""}`}
              onClick={() => setF("plan", p.id)}>
              {p.popular && <span className="af-plan-pop">★ {window.useEyad().lang === "ar" ? "الأكثر اختيارًا" : "Most popular"}</span>}
              <div className="af-plan-name">{p.name}</div>
              <div className="af-plan-price">
                <span className="num">{p.price}</span>
                <span className="cur">{s.currency}</span>
                <span className="per">{p.period}</span>
              </div>
              <div className="af-plan-desc">{p.desc}</div>
              <ul className="af-plan-feats">
                {p.feats.map((f, i) => (
                  <li key={i}><span className="dot"><Icon name="check" size={11}/></span>{f}</li>
                ))}
              </ul>
              <div className="af-plan-pick">
                {on ? <><Icon name="check" size={14}/> {s.selected}</> : s.choose}
              </div>
            </button>
          );
        })}
      </div>
      {errs.plan && <div className="af-err">{errs.plan}</div>}
    </>
  );
}

function RegisterDone({ form, onSignedIn, onClose, t }) {
  const d = t.auth.register.done;
  return (
    <div className="auth-success">
      <div className="auth-check"><Icon name="check" size={32}/></div>
      <h2>{d.title}</h2>
      <p>{d.body1} <strong>{form.studentName || "—"}</strong> {d.body2}<br/><span className="en" style={{ direction: "ltr", display: "inline-block" }}>{form.email}</span></p>
      <div className="auth-tip">{d.tip}</div>
      <div className="auth-success-actions">
        <button className="btn btn-primary" onClick={onSignedIn}>
          {d.btn}
          <Icon name="arrow" size={16}/>
        </button>
        <button className="btn btn-ghost" onClick={onClose}>{d.back}</button>
      </div>
    </div>
  );
}

Object.assign(window, { WhatsAppButton, LoginScreen, RegisterScreen });
