/* global React, ReactDOM, Icon */
const { useState, useEffect } = React;

// ====== ICONS we need beyond the existing icon set ======
const I = {
  mail: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/>
    </svg>
  ),
  lock: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 1 1 8 0v4"/>
    </svg>
  ),
  user: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="8" r="4"/><path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8"/>
    </svg>
  ),
  building: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="4" y="3" width="16" height="18" rx="1"/>
      <path d="M9 7h2M13 7h2M9 11h2M13 11h2M9 15h2M13 15h2"/>
      <path d="M10 21v-3h4v3"/>
    </svg>
  ),
  phone: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.86 19.86 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.86 19.86 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>
    </svg>
  ),
  eye: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" 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>
  ),
  eyeOff: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><path d="M1 1l22 22"/>
    </svg>
  ),
  arrow: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14M13 5l7 7-7 7"/>
    </svg>
  ),
  google: () => (
    <svg viewBox="0 0 24 24">
      <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
      <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
      <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
      <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
    </svg>
  ),
  whatsapp: () => (
    <svg viewBox="0 0 24 24" fill="#25D366">
      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413Z"/>
    </svg>
  ),
  shield: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 2l9 4v6c0 5.55-3.84 10.74-9 12-5.16-1.26-9-6.45-9-12V6l9-4z"/>
    </svg>
  ),
  check: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12l5 5L20 7"/>
    </svg>
  ),
};

// ============== APP ==============
function AuthApp() {
  // mode from URL hash
  const initial = window.location.hash === '#daftar' ? 'register' : 'login';
  const [mode, setMode] = useState(initial);

  useEffect(() => {
    const onHash = () => setMode(window.location.hash === '#daftar' ? 'register' : 'login');
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const switchTo = (m) => {
    window.location.hash = m === 'register' ? 'daftar' : 'masuk';
    setMode(m);
  };

  return (
    <div className="auth-shell">
      <FormPanel mode={mode} switchTo={switchTo}/>
      <ShowcasePanel mode={mode}/>
    </div>
  );
}

// ============== LEFT — FORM PANEL ==============
function FormPanel({ mode, switchTo }) {
  return (
    <div className="auth-form-panel">
      <div className="auth-top">
        <a className="auth-brand" href="landing.html">
          <img src={window.__resources?.logo || "assets/simantep-logo.png"} alt="Simantep"/>
          <div className="auth-brand-text">
            <strong>Simantep</strong>
            <span>WMS</span>
          </div>
        </a>
        <div className="auth-top-link">
          {mode === 'login' ? (
            <>Belum punya akun? <a href="#daftar" onClick={(e)=>{e.preventDefault();switchTo('register');}}>Daftar gratis</a></>
          ) : (
            <>Sudah punya akun? <a href="#masuk" onClick={(e)=>{e.preventDefault();switchTo('login');}}>Masuk</a></>
          )}
        </div>
      </div>

      <div className="auth-form-wrap">
        {mode === 'login' ? <LoginForm/> : <RegisterForm/>}
      </div>

      <div className="auth-bottom">
        <span>© 2026 Simantep · Surabaya</span>
        <div className="auth-bottom-links">
          <a href="#">Bantuan</a>
          <a href="#">Privasi</a>
          <a href="#">Syarat</a>
        </div>
      </div>
    </div>
  );
}

// ============== LOGIN FORM ==============
function LoginForm() {
  const [showPwd, setShowPwd] = useState(false);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  const onSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setBusy(true);
    try {
      await window.Api.auth.signIn(email, password);
      window.location.href = 'index.html';
    } catch (err) {
      setError(err.body?.message || err.message || 'Gagal masuk');
      setBusy(false);
    }
  };

  return (
    <form className="auth-form" onSubmit={onSubmit}>
      <span className="auth-eyebrow"><I.shield/> Akses aman 256-bit</span>
      <h1 className="auth-title">Selamat datang <em>kembali</em>.</h1>
      <p className="auth-sub">Masuk untuk pantau pesanan, stok, dan kinerja toko Anda di seluruh marketplace.</p>

      <div className="auth-social">
        <button type="button" className="auth-social-btn"><I.google/> Google</button>
        <button type="button" className="auth-social-btn"><I.whatsapp/> WhatsApp</button>
      </div>

      <div className="auth-divider">atau pakai email</div>

      {error && (
        <div style={{
          padding:'10px 14px', borderRadius:8, marginBottom:12,
          background:'#fee2e2', color:'#991b1b', fontSize:13,
          border:'1px solid #fecaca'
        }}>{error}</div>
      )}

      <div className="auth-fields">
        <div className="auth-field">
          <label className="auth-label">Email</label>
          <div className="auth-input-wrap">
            <I.mail/>
            <input
              className="auth-input"
              type="email"
              placeholder="nama@bisnis.id"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              autoComplete="email"
            />
          </div>
        </div>

        <div className="auth-field">
          <label className="auth-label">
            Password
            <a href="#">Lupa password?</a>
          </label>
          <div className="auth-input-wrap">
            <I.lock/>
            <input
              className="auth-input"
              type={showPwd ? 'text' : 'password'}
              placeholder="••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              autoComplete="current-password"
            />
            <button type="button" className="auth-toggle-pwd" onClick={()=>setShowPwd(!showPwd)}>
              {showPwd ? <I.eyeOff/> : <I.eye/>}
            </button>
          </div>
        </div>

        <label className="auth-check">
          <input type="checkbox" defaultChecked/>
          <span>Ingat saya selama 30 hari di perangkat ini</span>
        </label>
      </div>

      <button type="submit" className="auth-submit" disabled={busy}>
        {busy ? 'Memproses…' : <>Masuk ke Dashboard <I.arrow/></>}
      </button>

      <p className="auth-foot">
        Belum gabung? <a href="#daftar" onClick={(e)=>{e.preventDefault(); window.location.hash='daftar';}}>Daftarkan toko Anda gratis</a>
      </p>
    </form>
  );
}

// ============== REGISTER FORM ==============
function RegisterForm() {
  const [showPwd, setShowPwd] = useState(false);
  const [pwd, setPwd] = useState('');
  const [name, setName] = useState('');
  const [businessName, setBusinessName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  // password strength
  const score = (() => {
    let s = 0;
    if (pwd.length >= 8) s++;
    if (/[A-Z]/.test(pwd) && /[a-z]/.test(pwd)) s++;
    if (/\d/.test(pwd)) s++;
    if (/[^A-Za-z0-9]/.test(pwd)) s++;
    return s;
  })();
  const strengthLabel = ['Terlalu lemah','Lemah','Cukup','Kuat','Sangat kuat'][score];

  const onSubmit = async (e) => {
    e.preventDefault();
    setError('');
    if (pwd.length < 8) {
      setError('Password minimal 8 karakter');
      return;
    }
    setBusy(true);
    try {
      await window.Api.auth.signUp({
        name,
        email,
        password: pwd,
        role: 'owner',
        businessName,
        phone,
      });
      // Better Auth's autoSignIn is enabled — session cookie set.
      window.location.href = 'index.html';
    } catch (err) {
      setError(err.body?.message || err.message || 'Gagal daftar');
      setBusy(false);
    }
  };

  return (
    <form className="auth-form" onSubmit={onSubmit}>
      <span className="auth-eyebrow"><I.check/> 14 hari gratis · Tanpa kartu kredit</span>
      <h1 className="auth-title">Mulai titip stok di <em>Simantep</em>.</h1>
      <p className="auth-sub">Buat akun gratis. Hubungkan toko marketplace Anda dalam 5 menit.</p>

      <div className="auth-social">
        <button type="button" className="auth-social-btn"><I.google/> Daftar via Google</button>
        <button type="button" className="auth-social-btn"><I.whatsapp/> Pakai WhatsApp</button>
      </div>

      <div className="auth-divider">atau isi data berikut</div>

      {error && (
        <div style={{
          padding:'10px 14px', borderRadius:8, marginBottom:12,
          background:'#fee2e2', color:'#991b1b', fontSize:13,
          border:'1px solid #fecaca'
        }}>{error}</div>
      )}

      <div className="auth-fields">
        <div className="auth-field-row">
          <div className="auth-field">
            <label className="auth-label">Nama lengkap</label>
            <div className="auth-input-wrap">
              <I.user/>
              <input className="auth-input" type="text" placeholder="Budi Santoso"
                value={name} onChange={(e)=>setName(e.target.value)} required/>
            </div>
          </div>
          <div className="auth-field">
            <label className="auth-label">Nama bisnis</label>
            <div className="auth-input-wrap">
              <I.building/>
              <input className="auth-input" type="text" placeholder="Berkah Jaya"
                value={businessName} onChange={(e)=>setBusinessName(e.target.value)} required/>
            </div>
          </div>
        </div>

        <div className="auth-field">
          <label className="auth-label">Email bisnis</label>
          <div className="auth-input-wrap">
            <I.mail/>
            <input className="auth-input" type="email" placeholder="nama@bisnis.id"
              value={email} onChange={(e)=>setEmail(e.target.value)} required/>
          </div>
        </div>

        <div className="auth-field">
          <label className="auth-label">No. WhatsApp</label>
          <div className="auth-phone">
            <select defaultValue="+62">
              <option>+62</option>
              <option>+60</option>
              <option>+65</option>
              <option>+66</option>
            </select>
            <div className="auth-input-wrap">
              <I.phone/>
              <input className="auth-input" type="tel" placeholder="812-3456-7890"
                value={phone} onChange={(e)=>setPhone(e.target.value)} required/>
            </div>
          </div>
        </div>

        <div className="auth-field">
          <label className="auth-label">Buat password</label>
          <div className="auth-input-wrap">
            <I.lock/>
            <input
              className="auth-input"
              type={showPwd?'text':'password'}
              placeholder="Min. 8 karakter"
              value={pwd}
              onChange={(e)=>setPwd(e.target.value)}
              required
            />
            <button type="button" className="auth-toggle-pwd" onClick={()=>setShowPwd(!showPwd)}>
              {showPwd ? <I.eyeOff/> : <I.eye/>}
            </button>
          </div>
          {pwd && (
            <div className="pwd-strength">
              <div className={`pwd-strength-bar s${score}`}>
                <span/><span/><span/><span/>
              </div>
              <div className="pwd-strength-label">
                <span>Kekuatan password</span>
                <strong>{strengthLabel}</strong>
              </div>
            </div>
          )}
        </div>

        <label className="auth-check">
          <input type="checkbox" required/>
          <span>Saya setuju dengan <a href="#">Syarat Layanan</a> dan <a href="#">Kebijakan Privasi</a> Simantep</span>
        </label>
      </div>

      <button type="submit" className="auth-submit" disabled={busy}>
        {busy ? 'Memproses…' : <>Buat Akun &amp; Mulai <I.arrow/></>}
      </button>

      <p className="auth-foot">
        Sudah punya akun? <a href="#masuk" onClick={(e)=>{e.preventDefault(); window.location.hash='masuk';}}>Masuk di sini</a>
      </p>
    </form>
  );
}

// ============== RIGHT — SHOWCASE ==============
function ShowcasePanel({ mode }) {
  return (
    <div className="auth-showcase">
      <span className="showcase-eyebrow">
        <span className="pulse"/>
        Real-time · 6 marketplace tersinkron
      </span>

      <h2 className="showcase-headline">
        {mode === 'login'
          ? <>Pesanan terus jalan, <em>stok aman</em>.</>
          : <>Titip stok, kami yang <em>packing &amp; kirim</em>.</>}
      </h2>
      <p className="showcase-sub">
        {mode === 'login'
          ? 'Dashboard satu pintu untuk seluruh kanal jualan Anda. Pantau, scan, kirim — semuanya dari satu layar.'
          : 'Gabung 2.400+ seller yang sudah pakai Simantep. Stok di gudang kami, pesanan dari mana saja, tim kami yang kerjakan sisanya.'}
      </p>

      <div className="showcase-preview">
        <div className="showcase-preview-head">
          <div className="dots"><span/><span/><span/></div>
          <span className="url">simantep.id/dashboard</span>
        </div>

        <div className="showcase-stats">
          <div className="showcase-stat">
            <div className="showcase-stat-label">Pesanan</div>
            <div className="showcase-stat-value">142</div>
            <div className="showcase-stat-delta">↑ 18% hari ini</div>
          </div>
          <div className="showcase-stat">
            <div className="showcase-stat-label">Pendapatan</div>
            <div className="showcase-stat-value">24,8jt</div>
            <div className="showcase-stat-delta">↑ 12% MoM</div>
          </div>
          <div className="showcase-stat">
            <div className="showcase-stat-label">Diproses</div>
            <div className="showcase-stat-value">38</div>
            <div className="showcase-stat-delta warn">9 dekat SLA</div>
          </div>
        </div>

        <div className="showcase-mini-bars">
          {[42,58,51,73,65,88,79,92,84,105,98,124,118,142].map((v,i) => (
            <span key={i} style={{ height:`${(v/142)*100}%` }}/>
          ))}
        </div>

        <div className="showcase-list">
          <div className="showcase-list-row">
            <span className="mp-dot" style={{ background:'#ee4d2d' }}>S</span>
            <span className="id">SMP-A8X42K</span>
            <span className="name">Andi Wijaya</span>
            <span className="chip-mini">Packed</span>
          </div>
          <div className="showcase-list-row">
            <span className="mp-dot" style={{ background:'#000' }}>T</span>
            <span className="id">SMP-T7Y19P</span>
            <span className="name">Sari Indah</span>
            <span className="chip-mini">Shipped</span>
          </div>
          <div className="showcase-list-row">
            <span className="mp-dot" style={{ background:'#03ac0e' }}>T</span>
            <span className="id">SMP-K3M88L</span>
            <span className="name">Joko Prasetyo</span>
            <span className="chip-mini">Packed</span>
          </div>
        </div>
      </div>

      <div className="showcase-proof">
        <div className="showcase-proof-avatars">
          <span style={{ background:'#ed3a1a' }}>BS</span>
          <span style={{ background:'#1f6fd9' }}>AN</span>
          <span style={{ background:'#1c8e5a' }}>RM</span>
          <span style={{ background:'#c47a06' }}>SN</span>
        </div>
        <div className="showcase-proof-text">
          <strong>2.400+ seller</strong> sudah titip stok di Simantep<br/>
          <span style={{ color:'rgba(255,255,255,0.55)', fontSize:12 }}>Mulai Rp 2.000/packing · 3 gudang nasional</span>
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<AuthApp/>);
