/* global React, I, portalApi */
async function firebaseRequest(config, action, body) {
  let response, data;
  try {
    response = await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:${action}?key=${encodeURIComponent(config.apiKey)}`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(15000),
    });
    data = await response.json();
  } catch { throw new Error('We could not reach account services. Check your connection and try again.'); }
  if (!response.ok) {
    const code = data.error?.message?.split(' : ')[0];
    const messages = { EMAIL_EXISTS: 'That email already has an account. Sign in or reset your password.',
      INVALID_LOGIN_CREDENTIALS: 'The email or password is incorrect.', INVALID_PASSWORD: 'The email or password is incorrect.',
      EMAIL_NOT_FOUND: 'The email or password is incorrect.', TOO_MANY_ATTEMPTS_TRY_LATER: 'Too many attempts. Please try again later.',
      OPERATION_NOT_ALLOWED: 'This sign-in method is not available yet. Please contact the studio.',
      USER_DISABLED: 'This account is unavailable. Please contact the studio.',
      INVALID_EMAIL: 'Enter a valid email address.', WEAK_PASSWORD: 'Please use a stronger password.',
      PASSWORD_DOES_NOT_MEET_REQUIREMENTS: 'Your password does not meet the account security requirements. Please choose a stronger password.' };
    throw new Error(messages[code] || 'Account services could not complete this request. Please retry or contact the studio.');
  }
  return data;
}
function AccountEntry({ mode = 'login' }) {
  const [config, setConfig] = React.useState(null), [loading, setLoading] = React.useState(true);
  const [email, setEmail] = React.useState(''), [password, setPassword] = React.useState('');
  const [busy, setBusy] = React.useState(false), [error, setError] = React.useState(''), [notice, setNotice] = React.useState('');
  const [retry, setRetry] = React.useState(0);
  React.useEffect(() => {
    let active = true; setLoading(true); setError(''); setNotice('');
    portalApi('auth-config').then(data => { if (active) { setConfig(data.firebase); if (!data.firebase) setError('Account access is being prepared. You can still explore our work or talk to the team.'); } })
      .catch(e => { if (active) setError(e.message); }).finally(() => { if (active) setLoading(false); });
    return () => { active = false; };
  }, [retry]);
  React.useEffect(() => { setPassword(''); setError(''); setNotice(''); }, [mode]);
  async function submit(e) {
    e.preventDefault(); if (!config || busy) return;
    setBusy(true); setError(''); setNotice('');
    try {
      if (mode === 'recovery') {
        // Show a receipt only after Firebase accepts the request. Never imply delivery was confirmed.
        await firebaseRequest(config, 'sendOobCode', { requestType: 'PASSWORD_RESET', email });
        setNotice('Firebase accepted the reset request. Check your inbox and spam folder for the next step.');
      } else {
        const result = await firebaseRequest(config, mode === 'register' ? 'signUp' : 'signInWithPassword', { email, password, returnSecureToken: true });
        setPassword('');
        await portalApi('firebase-session', { idToken: result.idToken });
        // ID and refresh tokens remain in this function's memory, never localStorage or the app database.
        window.location.assign('/portal');
      }
    } catch (e) { setError(e.message); } finally { setBusy(false); }
  }
  return <main className="account-entry"><div className="account-story"><span className="launch-eyebrow">YOUR ELEVEN VIEWS ACCOUNT</span><h1>Start with<br /><em>an idea.</em></h1><p>One place for your projects and the work you want to make. Connect AI when you need it. Keep working when you don’t.</p><div className="account-benefits"><span>PRIVATE PROJECTS</span><span>SAVED BRIEFS</span><span>YOUR PACE</span></div><a href="/work">Prefer a personal touch? Meet our work ↗</a></div>
    <section className="account-form-wrap"><span className="launch-eyebrow">{mode === 'register' ? 'A PLACE TO BEGIN' : mode === 'recovery' ? 'ACCOUNT RECOVERY' : 'WELCOME BACK'}</span><h2>{mode === 'register' ? 'Make it yours.' : mode === 'recovery' ? 'A fresh start.' : 'Pick up your project.'}</h2><p>{mode === 'register' ? 'Create your free Eleven Views account. No Puter connection or AI balance required.' : mode === 'recovery' ? 'Request password recovery through Firebase, our account provider.' : 'Sign in with your Eleven Views Firebase account.'}</p>
      <form onSubmit={submit}><label htmlFor="account-email">Email address</label><input id="account-email" required autoComplete="username" type="email" maxLength={254} value={email} onChange={e => setEmail(e.target.value)} placeholder="you@yourbrand.com" disabled={busy} />
        {mode !== 'recovery' && <><label htmlFor="account-password">{mode === 'register' ? 'Choose a password' : 'Password'}</label><input id="account-password" required type="password" autoComplete={mode === 'register' ? 'new-password' : 'current-password'} minLength={mode === 'register' ? 12 : 1} maxLength={128} value={password} onChange={e => setPassword(e.target.value)} disabled={busy} />{mode === 'register' && <small>Use at least 12 characters. Firebase manages your credentials.</small>}</>}
        {error && <p className="portal-alert" role="alert">{error}</p>}{notice && <p className="account-notice" role="status">{notice}</p>}
        <button className="btn btn-gold btn-lg" disabled={!config || loading || busy}>{loading ? 'Checking account services…' : busy ? 'Please wait…' : mode === 'register' ? 'Create account' : mode === 'recovery' ? 'Request reset email' : 'Sign in'}<I name="arrow" size={15} /></button>
      </form>{!loading && !config && <button className="account-link-button" onClick={() => setRetry(n => n + 1)}>Retry account services</button>}
      <div className="account-links">{mode !== 'register' && <a href="/register">Create a free account ↗</a>}{mode !== 'login' && <a href="/login">Already have an account? Sign in</a>}{mode === 'login' && <a href="/recover">Forgot your password?</a>}</div>
      <p className="account-fine">Invited through a private client link? <a href="/portal">Open your workspace</a>. Public browsing does not require an account. Read our <a href="/privacy">privacy policy</a> and <a href="/terms">terms</a>.</p>
    </section></main>;
}
function CustomerProjects() {
  const [user, setUser] = React.useState(null), [items, setItems] = React.useState([]), [checking, setChecking] = React.useState(true);
  const [error, setError] = React.useState(''), [busy, setBusy] = React.useState(false), [draft, setDraft] = React.useState(null), [notice, setNotice] = React.useState('');
  async function reload() { const data = await portalApi('projects'); setItems(data.projects); }
  React.useEffect(() => {
    let active = true;
    portalApi('session').then(async data => {
      if (!active) return; setUser(data.user);
      if (data.user.role !== 'client') throw new Error('Studio operators can manage client work in Client inbox.');
      const projects = await portalApi('projects'); if (active) setItems(projects.projects);
    }).catch(e => { if (active) { if (e.status === 401) window.location.replace('/login'); else setError(e.message); } }).finally(() => { if (active) setChecking(false); });
    return () => { active = false; };
  }, []);
  async function save(e) {
    e.preventDefault(); setBusy(true); setError(''); setNotice('');
    try { const result = await portalApi(draft.id ? 'project-update' : 'project-create', draft); setDraft(result.project); await reload(); setNotice('Saved to your private workspace.'); }
    catch(e) { setError(e.message); } finally { setBusy(false); }
  }
  async function open(item) {
    setBusy(true); setError(''); setNotice('');
    try { const data = await portalApi('project', undefined, { id: item.id }); setDraft(data.project); }
    catch(e) { setError(e.message); } finally { setBusy(false); }
  }
  async function logout() {
    setBusy(true); setError('');
    try { await portalApi('logout', {}); setUser(null); setItems([]); setDraft(null); window.location.assign('/login'); }
    catch(e) { setError(e.message); setBusy(false); }
  }
  function download() {
    const body = `# ${draft.name}\n\nGoal: ${draft.goal}\nRevision: ${draft.revision}\n\n${draft.brief}\n`;
    const url = URL.createObjectURL(new Blob([body], {type:'text/markdown;charset=utf-8'}));
    const a = window.document.createElement('a'); a.href=url; a.download=`${draft.name.replace(/[^a-z0-9 -]/gi,'').slice(0,80) || 'project'}-brief.md`; a.click(); setTimeout(() => URL.revokeObjectURL(url),1000);
  }
  if (checking) return <main className="portal-loading" role="status">Opening your projects…</main>;
  return <main className="customer-projects"><header><div><span className="launch-eyebrow">YOUR ELEVEN VIEWS WORKSPACE</span><h1>Your next chapter.</h1><p>{user ? `Welcome, ${user.name}. Start something. Keep it moving.` : 'Sign in to work on your projects.'}</p></div><div className="launch-actions"><a className="btn btn-line" href="/portal">Client inbox ↗</a>{user && <button className="btn btn-line" disabled={busy} onClick={logout}>Sign out</button>}</div></header>
    {error && <p className="portal-alert" role="alert">{error}</p>}
    {user?.role === 'client' && <div className="projects-layout"><aside><button className="btn btn-gold" disabled={busy} onClick={() => {setDraft({name:'',brief:'',goal:'launch'});setNotice('');setError('');}}>New project <I name="plus" size={15} /></button><div className="project-list">{items.map(p => <button key={p.id} disabled={busy} className={draft?.id === p.id ? 'selected' : ''} onClick={() => open(p)}><span>{p.goal.toUpperCase()} / REV {p.revision}</span><strong>{p.name}</strong><small>{new Date(p.updated_at).toLocaleDateString()}</small></button>)}</div></aside>
      <section className="project-editor">{draft ? <form onSubmit={save}><span className="launch-eyebrow">{draft.id ? 'YOUR SAVED PROJECT' : 'A NEW BEGINNING'}</span><label htmlFor="project-name">Project name</label><input id="project-name" required maxLength={120} value={draft.name} onChange={e => setDraft({...draft,name:e.target.value})} placeholder="What are you working on?" />
        <label htmlFor="project-goal">What’s the goal?</label><select id="project-goal" value={draft.goal} onChange={e => setDraft({...draft,goal:e.target.value})}><option value="launch">Launch something new</option><option value="grow">Grow what I have</option></select>
        <label htmlFor="project-brief">Your brief</label><textarea id="project-brief" maxLength={20000} rows={12} value={draft.brief} onChange={e => setDraft({...draft,brief:e.target.value})} placeholder="Tell us about the business, who it’s for, and what you want to make. You can refine this anytime." />
        {notice && <p className="account-notice" role="status">{notice}</p>}<div className="launch-actions"><button className="btn btn-gold" disabled={busy}>{busy?'Saving…':'Save project'}<I name="check" size={15}/></button>{draft.id && <button type="button" className="btn btn-line" onClick={download}>Download current brief ↗</button>}</div><p className="account-fine">No AI calls are used to save or edit this brief. This is a project brief, not a generated website. <a href="/contact">Ask our team for help ↗</a></p>
      </form> : <div className="projects-empty"><span className="launch-eyebrow">ROOM FOR WHAT’S NEXT</span><h2>Every good project<br />starts somewhere.</h2><p>Create a project, put your ideas into a brief and come back when you’re ready. No AI balance needed.</p><button className="btn btn-gold" onClick={() => setDraft({name:'',brief:'',goal:'launch'})}>Start your first project ↗</button></div>}</section>
    </div>}
  </main>;
}
window.AccountEntry = AccountEntry;
window.CustomerProjects = CustomerProjects;
