// Shared login logic + small UI atoms used by both V1 and V2.
// All components are exposed on window at the bottom.

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

function useLoginForm() {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [showPw, setShowPw] = React.useState(false);
  const [remember, setRemember] = React.useState(true);
  const [touched, setTouched] = React.useState({ email: false, password: false });
  const [submitState, setSubmitState] = React.useState('idle'); // idle | loading | success | error

  const emailErr =
    touched.email && !email ? 'E-posta gerekli'
    : touched.email && !EMAIL_RE.test(email) ? 'Geçerli bir e-posta adresi girin'
    : '';
  const pwErr = touched.password && !password ? 'Şifre gerekli' : '';

  const canSubmit = EMAIL_RE.test(email) && password.length > 0 && submitState !== 'loading';

  function submit() {
    setTouched({ email: true, password: true });
    if (!EMAIL_RE.test(email) || !password) return;
    setSubmitState('loading');
    setTimeout(() => setSubmitState('success'), 1400);
  }

  function reset() {
    setSubmitState('idle');
    setPassword('');
    setTouched({ email: false, password: false });
  }

  return {
    email, setEmail,
    password, setPassword,
    showPw, setShowPw,
    remember, setRemember,
    touched, setTouched,
    emailErr, pwErr, canSubmit,
    submitState, submit, reset,
  };
}

// — Icons (minimal, single-color, currentColor)
function IconEye({ 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 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z" />
      <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.6 6.2A10.9 10.9 0 0 1 12 6c6.5 0 10 6 10 6a17.7 17.7 0 0 1-3.3 4" />
      <path d="M6.6 6.6A17.6 17.6 0 0 0 2 12s3.5 6 10 6c1.6 0 3-.3 4.3-.8" />
      <path d="M9.9 9.9a3 3 0 0 0 4.2 4.2" />
    </svg>
  );
}

function IconMail() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="18" height="14" rx="2" />
      <path d="M3 7l9 6 9-6" />
    </svg>
  );
}

function IconLock() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="4" y="11" width="16" height="10" rx="2" />
      <path d="M8 11V7a4 4 0 0 1 8 0v4" />
    </svg>
  );
}

function IconCheck() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20 6L9 17l-5-5" />
    </svg>
  );
}

function IconSun() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="4" />
      <path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4" />
    </svg>
  );
}
function IconMoon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z" />
    </svg>
  );
}

// — Marka işareti (mark-color: mavi tile + beyaz chevron — her temada çalışır)
function LogoPlaceholder({ size = 'md' }) {
  const sizes = { sm: 36, md: 48, lg: 56 };
  const px = sizes[size] || sizes.md;
  return (
    <img
      src="images/logo/mark-color.svg"
      alt="IT Talep Sistemi"
      width={px} height={px}
      style={{ display: 'block', borderRadius: 10 }}
    />
  );
}

// — Dark mode toggle pill (inline, top-right of each artboard)
function DarkToggle({ dark, onToggle }) {
  return (
    <button
      onClick={onToggle}
      title={dark ? 'Açık temaya geç' : 'Koyu temaya geç'}
      style={{
        appearance: 'none', border: 'none', cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '7px 11px',
        borderRadius: 999,
        background: dark ? 'rgba(255,255,255,0.06)' : 'rgba(15,23,42,0.04)',
        boxShadow: dark ? 'inset 0 0 0 1px rgba(255,255,255,0.10)' : 'inset 0 0 0 1px rgba(15,23,42,0.08)',
        color: dark ? '#CBD5E1' : '#475569',
        fontSize: 12, fontWeight: 500,
        fontFamily: 'inherit',
      }}>
      {dark ? <IconSun /> : <IconMoon />}
      <span>{dark ? 'Açık' : 'Koyu'}</span>
    </button>
  );
}

// — Forgot password modal
function ForgotModal({ open, onClose, dark }) {
  const [val, setVal] = React.useState('');
  const [sent, setSent] = React.useState(false);
  React.useEffect(() => {
    if (open) { setVal(''); setSent(false); }
  }, [open]);
  if (!open) return null;

  const c = dark
    ? { bg: '#0F172A', text: '#F1F5F9', muted: '#94A3B8', border: '#1F2A3D', input: '#0B1220' }
    : { bg: '#FFFFFF', text: '#0F172A', muted: '#64748B', border: '#E2E8F0', input: '#F8FAFC' };

  return (
    <div
      onClick={onClose}
      style={{
        position: 'absolute', inset: 0, zIndex: 50,
        background: 'rgba(2,6,23,0.55)',
        backdropFilter: 'blur(4px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 24,
        animation: 'fadeIn 160ms ease-out',
      }}>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: 'min(440px, 100%)',
          background: c.bg, color: c.text,
          borderRadius: 16, padding: 28,
          boxShadow: '0 24px 60px -12px rgba(2,6,23,0.45), 0 0 0 1px ' + (dark ? 'rgba(255,255,255,0.06)' : 'rgba(15,23,42,0.05)'),
          animation: 'popIn 180ms cubic-bezier(.2,.9,.3,1.2)',
        }}>
        {!sent ? (
          <React.Fragment>
            <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 6 }}>Şifrenizi mi unuttunuz?</div>
            <div style={{ fontSize: 13.5, color: c.muted, lineHeight: 1.55, marginBottom: 20 }}>
              Kurumsal e-postanızı girin, sıfırlama bağlantısı gönderelim.
            </div>
            <label style={{ display: 'block', fontSize: 12.5, fontWeight: 500, color: c.muted, marginBottom: 6 }}>E-posta</label>
            <input
              type="email"
              value={val}
              onChange={(e) => setVal(e.target.value)}
              placeholder="ad.soyad@sirket.com"
              autoFocus
              style={{
                width: '100%', boxSizing: 'border-box',
                padding: '11px 14px',
                background: c.input, color: c.text,
                border: `1px solid ${c.border}`, borderRadius: 10,
                fontSize: 14, fontFamily: 'inherit', outline: 'none',
              }}
            />
            <div style={{ display: 'flex', gap: 10, marginTop: 22, justifyContent: 'flex-end' }}>
              <button onClick={onClose} style={{
                appearance: 'none', cursor: 'pointer',
                padding: '10px 16px', borderRadius: 10,
                background: 'transparent', color: c.text,
                border: `1px solid ${c.border}`,
                fontSize: 13.5, fontWeight: 500, fontFamily: 'inherit',
              }}>Vazgeç</button>
              <button
                onClick={() => EMAIL_RE.test(val) && setSent(true)}
                disabled={!EMAIL_RE.test(val)}
                style={{
                  appearance: 'none', cursor: EMAIL_RE.test(val) ? 'pointer' : 'not-allowed',
                  padding: '10px 18px', borderRadius: 10,
                  background: EMAIL_RE.test(val) ? '#2563EB' : (dark ? 'rgba(255,255,255,0.08)' : '#E2E8F0'),
                  color: EMAIL_RE.test(val) ? '#fff' : c.muted,
                  border: 'none', fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
                  transition: 'background 120ms',
                }}>Bağlantı gönder</button>
            </div>
          </React.Fragment>
        ) : (
          <div style={{ textAlign: 'center', padding: '8px 0 4px' }}>
            <div style={{
              width: 56, height: 56, borderRadius: 999,
              background: 'rgba(16,185,129,0.12)', color: '#10B981',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              marginBottom: 16,
            }}><IconCheck /></div>
            <div style={{ fontSize: 17, fontWeight: 600, marginBottom: 6 }}>Bağlantı gönderildi</div>
            <div style={{ fontSize: 13.5, color: c.muted, lineHeight: 1.55, marginBottom: 22 }}>
              <strong style={{ color: c.text, fontWeight: 600 }}>{val}</strong> adresine sıfırlama bağlantısı gönderdik. Gelen kutunuzu kontrol edin.
            </div>
            <button onClick={onClose} style={{
              appearance: 'none', cursor: 'pointer',
              padding: '10px 22px', borderRadius: 10,
              background: '#2563EB', color: '#fff',
              border: 'none', fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
            }}>Tamam</button>
          </div>
        )}
      </div>
    </div>
  );
}

// — Microsoft "windows" mark for SSO button (4-square logo, generic geometry)
function MSMark() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">
      <rect x="0" y="0" width="7" height="7" fill="#F25022" />
      <rect x="9" y="0" width="7" height="7" fill="#7FBA00" />
      <rect x="0" y="9" width="7" height="7" fill="#00A4EF" />
      <rect x="9" y="9" width="7" height="7" fill="#FFB900" />
    </svg>
  );
}

Object.assign(window, {
  useLoginForm, EMAIL_RE,
  IconEye, IconMail, IconLock, IconCheck, IconSun, IconMoon, MSMark,
  LogoPlaceholder, DarkToggle, ForgotModal,
});
