/* ===========================================================
   Forja 3D — Camada de nuvem (Supabase)
   Auth por e-mail/senha + workspace compartilhado (1 linha JSONB)
   + sincronização em tempo real. Exposto em window.cloud / Login.
   =========================================================== */
const SUPABASE_URL  = 'https://gfmroinpwvvmzgsmgsri.supabase.co';
const SUPABASE_ANON = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImdmbXJvaW5wd3Z2bXpnc21nc3JpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODEwNTA2MDYsImV4cCI6MjA5NjYyNjYwNn0.jzt-D6FRdgmqM73OUHwTWvpIEcT24uoyja1g5_MvQo8';
const WORKSPACE_ID  = 'forja';

const _db = (window.supabase && window.supabase.createClient)
  ? window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON, { auth: { persistSession: true, autoRefreshToken: true } })
  : null;

let _saveTimer = null;
let _lastPushed = null;

const cloud = {
  ok: !!_db,
  client: _db,

  async getSession() {
    if (!_db) return null;
    const { data } = await _db.auth.getSession();
    return data.session;
  },
  onAuth(cb) {
    if (!_db) return { unsubscribe() {} };
    const { data } = _db.auth.onAuthStateChange((_e, session) => cb(session));
    return data.subscription;
  },
  signIn(email, password) { return _db.auth.signInWithPassword({ email, password }); },
  async signOut() { if (_db) await _db.auth.signOut(); },

  async loadWorkspace() {
    if (!_db) return { error: { message: 'Supabase não carregou' } };
    const { data, error } = await _db.from('workspace').select('data').eq('id', WORKSPACE_ID).maybeSingle();
    if (error) return { error };
    return { data: data ? data.data : null };
  },

  saveWorkspace(stateObj) {
    if (!_db) return;
    clearTimeout(_saveTimer);
    _saveTimer = setTimeout(async () => {
      _lastPushed = JSON.stringify(stateObj);
      const { error } = await _db.from('workspace')
        .update({ data: stateObj, updated_at: new Date().toISOString() })
        .eq('id', WORKSPACE_ID);
      if (error) console.warn('[cloud] save error', error.message);
    }, 600);
  },

  subscribe(onRemote) {
    if (!_db) return null;
    return _db.channel('ws-' + WORKSPACE_ID)
      .on('postgres_changes',
        { event: 'UPDATE', schema: 'public', table: 'workspace', filter: 'id=eq.' + WORKSPACE_ID },
        (payload) => {
          const s = JSON.stringify(payload.new.data);
          if (s === _lastPushed) return; // ignora o eco da própria escrita
          onRemote(payload.new.data);
        })
      .subscribe();
  },

  removeChannel(ch) { if (_db && ch) _db.removeChannel(ch); },
};

window.cloud = cloud;

/* ---------------- Tela de Login ---------------- */
function Login() {
  const [email, setEmail] = useState('');
  const [pw, setPw] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');

  async function submit(e) {
    e.preventDefault();
    setErr(''); setBusy(true);
    try {
      const { error } = await cloud.signIn(email.trim(), pw);
      if (error) setErr(traduzErro(error.message));
    } catch (ex) {
      setErr('Não consegui conectar. Verifique a internet.');
    }
    setBusy(false);
  }

  return (
    <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', padding: 20, background: 'radial-gradient(120% 90% at 80% -10%, #221a12 0%, var(--bg) 55%)' }}>
      <div style={{ width: '100%', maxWidth: 380 }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 30 }}>
          <img src="assets/revision-lockup.png" alt="Revision Studio 3D" style={{ width: 300, maxWidth: '90%', height: 'auto', mixBlendMode: 'screen' }} />
        </div>

        <form className="panel panel-pad" onSubmit={submit} style={{ padding: 26 }}>
          <div className="panel-t" style={{ fontSize: 14, marginBottom: 4 }}><span className="mark" />Entrar</div>
          <p className="muted" style={{ fontSize: 13, margin: '8px 0 20px' }}>Acesso restrito — só você e seu sócio.</p>

          <Field label="E-mail">
            <input className="inp" type="email" autoFocus value={email} onChange={(e) => setEmail(e.target.value)} placeholder="voce@email.com" required />
          </Field>
          <Field label="Senha">
            <input className="inp" type="password" value={pw} onChange={(e) => setPw(e.target.value)} placeholder="••••••••" required />
          </Field>

          {err && <div style={{ background: 'var(--red-soft)', color: 'var(--red)', fontSize: 13, padding: '10px 12px', borderRadius: 8, marginBottom: 14 }}>{err}</div>}

          <button className="btn btn-primary" type="submit" disabled={busy} style={{ width: '100%', justifyContent: 'center', opacity: busy ? .6 : 1 }}>
            {busy ? 'Entrando…' : 'Entrar'}
          </button>
        </form>

        {!cloud.ok && <div style={{ textAlign: 'center', color: 'var(--red)', fontSize: 12, marginTop: 14 }}>⚠ Biblioteca do banco não carregou (sem internet?).</div>}
        <p className="muted" style={{ textAlign: 'center', fontSize: 11.5, marginTop: 18, lineHeight: 1.6 }}>Os acessos são criados no painel do Supabase.<br />Não existe cadastro aberto.</p>
      </div>
    </div>
  );
}

function traduzErro(msg) {
  if (/Invalid login/i.test(msg)) return 'E-mail ou senha incorretos.';
  if (/Email not confirmed/i.test(msg)) return 'E-mail ainda não confirmado no Supabase.';
  if (/network|fetch/i.test(msg)) return 'Falha de conexão com o banco.';
  return msg;
}

window.Login = Login;
