// MailSettings: the Email page (admin). Sets the account the Support Hub sends email from, and sends a test message.
// Reuses the layout styles from ClientsView.jsx. Exports: MailSettingsView

const MS_CSS = () => `
.ms-wrap { max-width: 760px; margin: 0 auto; }
.ms-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px 16px; }
.ms-full { grid-column: 1 / -1; }
.ms-label { display: block; font-size: 11px; font-weight: 800; letter-spacing: .06em; text-transform: uppercase; color: ${CV.mute}; margin-bottom: 6px; }
.ms-field .cv-input { width: 100%; box-sizing: border-box; }
.ms-note { font-size: 12.5px; line-height: 1.5; color: ${CV.mute}; margin-top: 6px; }
.ms-state { display: flex; align-items: flex-start; gap: 12px; padding: 16px 18px; }
.ms-dot { width: 10px; height: 10px; border-radius: 50%; margin-top: 5px; flex-shrink: 0; }
.ms-alert { margin: 0 0 16px; padding: 12px 14px; border-radius: 10px; font-size: 13.5px; line-height: 1.5; }
.ms-bad { background: #FEF2F2; color: #B91C1C; border: 1px solid #FECACA; }
.ms-ok { background: #ECFDF5; color: #065F46; border: 1px solid #A7F3D0; }
.ms-check { display: flex; align-items: center; gap: 10px; font-size: 14px; color: ${CV.ink}; cursor: pointer; }
.ms-check input { width: 18px; height: 18px; accent-color: ${CV.navy}; }
.ms-steps { margin: 0; padding-left: 20px; font-size: 13.5px; line-height: 1.6; color: ${CV.mute}; }
.ms-steps li + li { margin-top: 4px; }
.ms-steps b { color: ${CV.ink}; }
.ms-row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
@media (max-width: 640px) { .ms-grid { grid-template-columns: minmax(0, 1fr); } }
`;

// Typing a full address picks the provider for you: someone@yahoo.com is Yahoo, and so on
const MS_DOMAINS = {
  'gmail.com': 'gmail', 'googlemail.com': 'gmail',
  'yahoo.com': 'yahoo', 'yahoo.in': 'yahoo', 'yahoo.co.in': 'yahoo', 'yahoo.co.uk': 'yahoo', 'ymail.com': 'yahoo', 'rocketmail.com': 'yahoo',
  'outlook.com': 'outlook', 'hotmail.com': 'outlook', 'live.com': 'outlook', 'msn.com': 'outlook',
  'icloud.com': 'icloud', 'me.com': 'icloud', 'mac.com': 'icloud', 'aol.com': 'aol',
  'zoho.com': 'zoho_com', 'zoho.in': 'zoho', 'zohomail.in': 'zoho',
};

function MailSettingsView() {
  const [data, setData]       = React.useState(null);
  const [f, setF]             = React.useState({ provider: 'gmail', host: 'smtp.gmail.com', port: 465, secure: true, user: '', password: '', from: '' });
  const [msg, setMsg]         = React.useState(null);       // { type: 'ok' | 'error', text }
  const touched = React.useRef(false);                    // the admin chose a provider by hand, so stop guessing
  const [saving, setSaving]   = React.useState(false);
  const [testing, setTesting] = React.useState(false);
  const [to, setTo]           = React.useState((window._synUser && window._synUser.email) || '');
  const [testMsg, setTestMsg] = React.useState(null);
  const h = () => ({ 'Content-Type': 'application/json', Authorization: 'Bearer ' + (localStorage.getItem('hub_token') || '') });

  function load(fill) {
    return fetch('/api/mail', { headers: h() }).then(r => r.json()).then(d => {
      setData(d);
      if (fill && d.server) setF({ provider: d.server.provider, host: d.server.host, port: d.server.port, secure: d.server.secure, user: d.server.user, password: '', from: d.server.from });
    });
  }
  React.useEffect(() => { load(true).catch(() => setMsg({ type: 'error', text: 'Could not load the email settings.' })); }, []);

  const set = (k, v) => setF(cur => ({ ...cur, [k]: v }));
  function pickProvider(p, byHand) {
    if (byHand) touched.current = true;
    const pr = data.providers[p];
    setF(cur => ({ ...cur, provider: p, ...(pr.host ? { host: pr.host } : {}), port: pr.port, secure: pr.secure, ...(pr.userValue && !cur.user ? { user: pr.userValue } : {}) }));
  }
  function changeUser(v) {
    const guess = MS_DOMAINS[(v.split('@')[1] || '').toLowerCase()];
    if (guess && !touched.current && !saved && guess !== f.provider) { pickProvider(guess, false); setF(cur => ({ ...cur, user: v, from: cur.from || v })); return; }
    setF(cur => ({ ...cur, user: v, ...(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) && !cur.from ? { from: v } : {}) }));
  }

  async function save(e) {
    e.preventDefault();
    setSaving(true); setMsg(null);
    try {
      const r = await fetch('/api/mail', { method: 'PUT', headers: h(), body: JSON.stringify({ ...f, port: Number(f.port) }) });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error || 'Could not save');
      setData(d); setF(cur => ({ ...cur, password: '' }));
      setMsg({ type: 'ok', text: 'Connected, and saved. Emails now go out through this account.' });
    } catch (err) { setMsg({ type: 'error', text: err.message }); }
    finally { setSaving(false); }
  }

  async function remove() {
    if (!window.confirm('Remove the saved email account? The app will go back to the server\'s own email settings, or send no email if there are none.')) return;
    setMsg(null);
    const r = await fetch('/api/mail', { method: 'DELETE', headers: h() });
    const d = await r.json();
    if (!r.ok) { setMsg({ type: 'error', text: d.error || 'Could not remove' }); return; }
    setData(d); setF({ provider: 'gmail', host: 'smtp.gmail.com', port: 465, secure: true, user: '', password: '', from: '' });
    setMsg({ type: 'ok', text: 'Removed.' });
  }

  async function sendTest() {
    setTesting(true); setTestMsg(null);
    try {
      const r = await fetch('/api/mail/test', { method: 'POST', headers: h(), body: JSON.stringify({ to }) });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error || 'Could not send');
      setTestMsg({ type: 'ok', text: `Sent to ${d.to} through the ${d.via}. Check that inbox.` });
      load(false);
    } catch (err) { setTestMsg({ type: 'error', text: err.message }); load(false); }
    finally { setTesting(false); }
  }

  if (!data) return <div className="cv1"><style>{CV_CSS + CV_PAGE_CSS + MS_CSS()}</style><div style={{ color: CV.faint, fontSize: 14 }}>Loading…</div></div>;

  const saved = data.server;
  const state = saved && !saved.needsPassword
    ? { color: '#17745A', title: `Sending through ${saved.host}`, text: `From ${saved.from}. Saved on this page.` }
    : data.serverDefault
      ? { color: '#1A5090', title: `Sending through the server's own email (${data.serverDefaultHost})`, text: data.serverDefaultHost === 'mailpit' ? 'This is the local Mailpit inbox, so nothing leaves this machine. Read it at http://localhost:8026.' : 'Set by SMTP_HOST on the server. Save an account below to use your own address instead.' }
      : { color: '#B45309', title: 'No email is being sent', text: 'Save an email account below, or set SMTP_HOST on the server.' };
  const preset = data.providers[f.provider];

  return (
    <div className="cv1">
      <style>{CV_CSS + CV_PAGE_CSS + MS_CSS()}</style>
      <div className="ms-wrap">
        <h2 style={{ margin: 0, fontSize: 28, fontWeight: 800, letterSpacing: '-0.02em', color: CV.navy }}>Email</h2>
        <p style={{ margin: '4px 0 20px', fontSize: 14, color: CV.mute }}>The account the Support Hub sends from: new concerns, assignments, "was this resolved?" and account emails.</p>

        <section className="cv-panel" style={{ padding: '18px 22px', marginBottom: 16 }}>
          <div style={{ fontSize: 14, fontWeight: 800, color: CV.navy, marginBottom: 8 }}>What this page does</div>
          <ol className="ms-steps">
            <li>Every email the Support Hub sends (new concerns, assignments, "was this resolved?", welcome and password emails) leaves from <b>one email account</b>. You choose it here.</li>
            <li>Pick your provider (Gmail, Yahoo, Outlook, iCloud, a business host or a sending service) and the server details fill in. Typing your address picks the provider for you.</li>
            <li>Most providers need an <b>app password</b>, not your normal one. The note under the provider says how to get it.</li>
            <li>Press <b>Save and test connection</b>. The Hub signs in once to check, and only saves if the server accepts it. Then send yourself a test email below.</li>
          </ol>
        </section>

        <section className="cv-panel ms-state" style={{ marginBottom: 16 }} aria-live="polite">
          <span className="ms-dot" style={{ background: state.color }} />
          <div><div style={{ fontSize: 15, fontWeight: 800, color: CV.navy }}>{state.title}</div><div style={{ fontSize: 13.5, color: CV.mute, marginTop: 2 }}>{state.text}</div></div>
        </section>

        {data.problem && <div role="alert" className="ms-alert ms-bad">{data.problem}</div>}

        <form className="cv-panel" style={{ padding: 22, marginBottom: 16 }} onSubmit={save}>
          <h3 style={{ margin: '0 0 16px', fontSize: 16, fontWeight: 800, color: CV.navy }}>Email account</h3>
          <div className="ms-grid">
            <label className="ms-field ms-full"><span className="ms-label">Provider</span>
              <select className="cv-input" value={f.provider} onChange={e => pickProvider(e.target.value, true)}>
                {[...new Set(Object.values(data.providers).map(p => p.group))].map(g => (
                  <optgroup key={g} label={g}>
                    {Object.entries(data.providers).filter(([, p]) => p.group === g).map(([k, p]) => <option key={k} value={k}>{p.label}</option>)}
                  </optgroup>
                ))}
              </select>
              <div className="ms-note">{preset.note}</div>
            </label>
            <label className="ms-field"><span className="ms-label">Mail server</span>
              <input className="cv-input" value={f.host} onChange={e => set('host', e.target.value)} placeholder="smtp.example.com" required />
            </label>
            <label className="ms-field"><span className="ms-label">Port</span>
              <input className="cv-input" type="number" value={f.port} onChange={e => set('port', e.target.value)} required />
            </label>
            <label className="ms-check ms-full"><input type="checkbox" checked={f.secure} onChange={e => set('secure', e.target.checked)} />Secure connection (use with port 465; leave off for 587)</label>
            <label className="ms-field"><span className="ms-label">Username</span>
              <input className="cv-input" value={f.user} onChange={e => changeUser(e.target.value)} placeholder="you@yourcompany.com" autoComplete="off" />
            </label>
            <label className="ms-field"><span className="ms-label">{preset.passwordLabel || 'Password'}</span>
              <input className="cv-input" type="password" value={f.password} onChange={e => set('password', e.target.value)} autoComplete="new-password"
                placeholder={saved && saved.passwordSaved ? 'Saved. Leave blank to keep it' : ''} />
            </label>
            <label className="ms-field ms-full"><span className="ms-label">From address</span>
              <input className="cv-input" type="email" value={f.from} onChange={e => set('from', e.target.value)} placeholder="support@yourcompany.com" required />
              <div className="ms-note">What people see as the sender. It must be an address this account may send from.</div>
            </label>
          </div>
          {msg && <div role={msg.type === 'error' ? 'alert' : 'status'} className={'ms-alert ' + (msg.type === 'error' ? 'ms-bad' : 'ms-ok')} style={{ margin: '16px 0 0' }}>{msg.text}</div>}
          <div className="ms-row" style={{ marginTop: 18 }}>
            <button className="cv-btn cv-primary" type="submit" disabled={saving}>{saving ? 'Connecting…' : 'Save and test connection'}</button>
            {saved && <button className="cv-btn cv-danger" type="button" onClick={remove}>Remove saved account</button>}
          </div>
        </form>

        <section className="cv-panel" style={{ padding: 22 }}>
          <h3 style={{ margin: '0 0 6px', fontSize: 16, fontWeight: 800, color: CV.navy }}>Send a test email</h3>
          <p className="ms-note" style={{ margin: '0 0 14px' }}>Sends one message through whatever is set up now.</p>
          <div className="ms-row">
            <input className="cv-input" style={{ flex: '1 1 260px' }} type="email" value={to} onChange={e => setTo(e.target.value)} placeholder="name@example.com" aria-label="Send the test to" />
            <button className="cv-btn cv-soft" type="button" onClick={sendTest} disabled={testing || !to}><IC name="send" size={14} />{testing ? 'Sending…' : 'Send test'}</button>
          </div>
          {testMsg && <div role={testMsg.type === 'error' ? 'alert' : 'status'} className={'ms-alert ' + (testMsg.type === 'error' ? 'ms-bad' : 'ms-ok')} style={{ margin: '14px 0 0' }}>{testMsg.text}</div>}
        </section>
      </div>
    </div>
  );
}

Object.assign(window, { MailSettingsView });
