/* 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 { const error = new Error('We could not reach account services. Check your connection and try again.'); error.code = 'NETWORK_ERROR'; throw error; }
  if (!response.ok) {
    const code = data.error?.message?.split(' : ')[0];
    if (action === 'sendOobCode' && code === 'EMAIL_NOT_FOUND') return {};
    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.' };
    const error = new Error(messages[code] || 'Account services could not complete this request. Please retry or contact the studio.');
    error.code = code;
    throw error;
  }
  return data;
}
function accountReturnPath(search = window.location.search) {
  const next = new URLSearchParams(search).get('next');
  if (!next) return ['/portal', '/projects'].includes(window.location.pathname)
    ? window.location.pathname + window.location.search : '/portal';
  if (/[\\\x00-\x20]/.test(next)) return '/portal';
  try {
    const url = new URL(next, window.location.origin);
    return url.origin === window.location.origin && ['/portal', '/projects'].includes(url.pathname)
      ? url.pathname + url.search : '/portal';
  } catch { return '/portal'; }
}
function accountEntryLink(path) {
  const next = accountReturnPath();
  const destination = path === '/login' ? '/portal' : path;
  return next === '/portal' ? destination : `${destination}?next=${encodeURIComponent(next)}`;
}
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(() => {
    if (mode === 'login' && window.location.pathname === '/login') {
      const workspacePath = `/portal${window.location.search}${window.location.hash}`;
      window.history.replaceState({ name: 'portal', params: {} }, '', workspacePath);
      window.dispatchEvent(new PopStateEvent('popstate'));
      return;
    }
    let active = true;
    portalApi('session').then(data => {
      if (active && data.user) window.location.replace(accountReturnPath());
    }).catch(() => {});
    return () => { active = false; };
  }, []);
  React.useEffect(() => {
    let active = true; setLoading(true); setError(''); setNotice('');
    portalApi('auth-config').then(data => { if (active) { setConfig(data.firebase); if (!data.firebase && mode === 'login') setNotice('Public account setup is unavailable in this preview. Invited and studio accounts can still sign in here.'); else if (!data.firebase && mode !== 'login') setNotice('Account setup is not configured in this preview.'); } })
      .catch(e => { if (active) { if (mode === 'login') setNotice('Public sign-in could not be reached. You can still try your workspace credentials.'); else 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 && mode !== 'login') || 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('If an account matches this email, check your inbox and spam folder for a password reset link.');
      } else if (mode === 'register') {
        const result = await firebaseRequest(config, 'signUp', { email, password, returnSecureToken: true });
        setPassword('');
        await portalApi('firebase-session', { idToken: result.idToken });
        window.location.assign(accountReturnPath());
      } else {
        let signedIn = false;
        if (config) {
          try {
            const result = await firebaseRequest(config, 'signInWithPassword', { email, password, returnSecureToken: true });
            await portalApi('firebase-session', { idToken: result.idToken });
            signedIn = true;
          } catch (providerError) {
            const credentialError = ['INVALID_LOGIN_CREDENTIALS', 'INVALID_PASSWORD', 'EMAIL_NOT_FOUND', 'NETWORK_ERROR'].includes(providerError.code);
            if (!credentialError && providerError.status !== 409) throw providerError;
          }
        }
        if (!signedIn) await portalApi('login', { email, password });
        setPassword('');
        window.location.assign(accountReturnPath());
      }
    } catch (e) { setError(e.message); } finally { setBusy(false); }
  }
  return <main className="account-entry"><div className="account-story"><a href="/" className="account-brand" aria-label="Eleven Views home"><Logo size={48}/><span>Eleven Views</span></a><span className="launch-eyebrow">YOUR WORK, TOGETHER</span><h1>A clear place<br />to move forward.</h1><p>Keep your projects, conversations and deliverables in one workspace. Start with a brief. Build the next version with Atlas.</p><div className="account-benefits"><span>Private projects</span><span>Saved conversations</span><span>Files & reviews</span></div><a href="/">← Back to Eleven Views</a></div>
    <section className={`account-form-wrap account-${mode}`} aria-labelledby="account-heading"><a href="/" className="account-brand account-brand-mobile" aria-label="Eleven Views home"><Logo size={68}/></a><span className="launch-eyebrow">{mode === 'register' ? 'GET STARTED' : mode === 'recovery' ? 'ACCOUNT RECOVERY' : 'WELCOME BACK'}</span><h2 id="account-heading">{mode === 'register' ? 'Create your account' : mode === 'recovery' ? 'Reset your password' : 'Sign in to your workspace'}</h2><p>{mode === 'register' ? 'Create a free account for your Eleven Views projects and saved work.' : mode === 'recovery' ? 'Enter your account email to request a password reset link.' : 'Use your Eleven Views email and password to continue.'}</p>
      <form onSubmit={submit}><label htmlFor="account-email">Email address</label><input id="account-email" required autoComplete="email" 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. Choose a password you don’t use elsewhere.</small>}</>}
        {error && <p className="portal-alert" role="alert">{error}</p>}{notice && <p className="account-notice" role="status">{notice}</p>}
        <button className="btn account-submit" disabled={((!config && mode !== 'login') || 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>
      <div className="account-links">{mode !== 'register' && <a href={accountEntryLink('/register')}>Create a free account</a>}{mode !== 'login' && <a href={accountEntryLink('/login')}>Back to sign in</a>}{mode === 'login' && <a href={accountEntryLink('/recover')}>Forgot your password?</a>}{!loading && !config && mode !== 'login' && <button type="button" className="account-link-button" onClick={() => setRetry(n => n + 1)}>Retry account services</button>}</div>
      <p className="account-fine">Use the email and password for your Eleven Views workspace. New invitations open from the link in your email.</p><p className="account-fine">By continuing, you agree to our <a href="/terms">terms</a> and acknowledge our <a href="/privacy">privacy policy</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('/portal'); 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('/portal'); }
    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;
