// concierge-chat.jsx — the customer-facing Concierge (site/concierge.html).
// Talks to /api/concierge, for signed-in members only, like Snap & Compare and
// the calculator: the page hides the chat and the endpoint checks the sign-in.
// The conversation id and its token live in this browser's localStorage, under
// the member's own key, so they can come back to the same chat; the server
// stores only a hash of the token.
const { useState, useRef, useEffect, useCallback } = React;

const API = (window.API_BASE || '') + '/api/concierge';
const KEY = 'iceev-concierge-v1';
const PKEY = 'iceev-concierge-personal';

const Spark = () => <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l2.2 6.3L20 10l-5.8 1.7L12 18l-2.2-6.3L4 10l5.8-1.7L12 2z"/></svg>;
const Thumb = ({ down }) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={down ? { transform: 'rotate(180deg)' } : null}><path d="M7 10v11H4V10zM7 10l4-8a2.5 2.5 0 0 1 3 2.5V9h5.5a2 2 0 0 1 2 2.3l-1.4 8A2 2 0 0 1 18.1 21H7"/></svg>;
const DocIcon = () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 4h16v13H7l-3 3z"/></svg>;

const PERSONAL_STARTERS = [
  'How much did I spend on charging in the last 30 days?',
  'Is public charging costing me much more than home?',
  "What's my car's real energy use?",
];
const STARTERS = [
  'Is an EV cheaper to run than my petrol car?',
  'I need front brake pads for a 2015 Toyota Corolla',
  'My Polo needs its 60 000 km service',
  "I'm looking for a used EV under R450 000",
  'Will loadshedding stop me charging at home?',
];

function personalPref() { try { return localStorage.getItem(PKEY) !== 'off'; } catch (e) { return true; } }
// Each member's chat is kept under their own key, so someone else signing in on
// the same browser never opens it. A chat from before sign-in was needed (the
// bare key) goes to whoever signs in first, as the server links it to them too.
function load(uid) {
  try {
    const k = KEY + ':' + uid;
    let v = localStorage.getItem(k);
    if (!v && (v = localStorage.getItem(KEY))) { localStorage.setItem(k, v); localStorage.removeItem(KEY); }
    return JSON.parse(v || 'null');
  } catch (e) { return null; }
}
function save(uid, v) { try { const k = KEY + ':' + uid; v ? localStorage.setItem(k, JSON.stringify(v)) : localStorage.removeItem(k); } catch (e) {} }

// The member's sign-in, or for a visitor on their free question, the
// browser's trial id (site/usage.js).
async function authHeader() {
  if (window.Usage) { try { return await Usage.headers(); } catch (e) { /* fall through */ } }
  try {
    if (!window.DB || !DB.configured || !DB.sb) return {};
    const { data } = await DB.sb.auth.getSession();
    const t = data && data.session && data.session.access_token;
    return t ? { authorization: 'Bearer ' + t } : {};
  } catch (e) { return {}; }
}

async function call(body) {
  const r = await fetch(API, {
    method: 'POST',
    headers: { 'content-type': 'application/json', ...(await authHeader()) },
    body: JSON.stringify(body),
  });
  let data = null;
  try { data = await r.json(); } catch (e) {}
  if (!r.ok) {
    const err = new Error((data && data.message) || 'Something went wrong. Please try again.');
    err.status = r.status; err.code = data && data.error;
    if (data && data.allowance) err.allowance = data.allowance;
    throw err;
  }
  return data;
}

function Message({ m, onFeedback, rated }) {
  if (m.role === 'system') return <div className="sysmsg">{m.content}</div>;
  const ai = m.role === 'assistant';
  return (
    <div className={'msg ' + (ai ? 'ai' : 'user')}>
      <div className={'avatar ' + (ai ? 'ai' : 'me')}>{ai ? <Spark/> : 'You'}</div>
      <div className="bubble">
        {ai && m.safety_critical && <div className="safety" role="alert">Safety first — if the car may be unsafe, stop driving it and contact a qualified professional or emergency services.</div>}
        <div className="txt">{m.content}</div>
        {ai && m.sources && m.sources.length > 0 && (
          <div className="src"><DocIcon/>
            <span>Source{m.sources.length > 1 ? 's' : ''}: {m.sources.map((s, i) => (
              <React.Fragment key={s.id}>{i ? ' · ' : ''}{s.url ? <a href={s.url} target="_blank" rel="noopener">{s.title}</a> : s.title}</React.Fragment>
            ))}</span>
          </div>
        )}
        {ai && m.personalised && <div className="src"><DocIcon/><span>Based on your profile and <a href="charge-log.html">charge log</a></span></div>}
        {ai && m.unverified && <div className="flag">Not verified against ICE → EV approved sources</div>}
        {ai && m.id && (
          <div className="fb" aria-label="Was this helpful?">
            <button className={rated === 'up' ? 'on' : ''} disabled={!!rated} onClick={() => onFeedback(m.id, 'up')} aria-label="Helpful"><Thumb/>Helpful</button>
            <button className={rated === 'down' ? 'on' : ''} disabled={!!rated} onClick={() => onFeedback(m.id, 'down')} aria-label="Not helpful"><Thumb down/>Not helpful</button>
          </div>
        )}
      </div>
    </div>
  );
}

function ConsentCard({ req, busy, onDecide }) {
  return (
    <div className="consent" role="region" aria-label="Consent to share your details">
      <h3>Share your details with a {req.partner_noun}?</h3>
      <div className="lst">
        {req.fields.map((f) => <span key={f.key} className={f.personal ? 'p' : ''}>{f.label}</span>)}
      </div>
      <p>{req.statement}</p>
      <div className="row">
        <button className="btn btn-accent btn-sm" disabled={busy} onClick={() => onDecide('grant')}>Yes, share these details</button>
        <button className="btn btn-ghost btn-sm" disabled={busy} onClick={() => onDecide('decline')}>Not now</button>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------- sign-in */
const SIGN_IN = 'auth.html?next=' + encodeURIComponent('concierge.html');
const EXPIRED = 'Your sign-in has expired. Sign in again to keep chatting.';

// Visitors get one question without an account; members a monthly allowance
// (lib/plans.js). The server's message is used when there is one.
function spentText(a) {
  if (!a || a.plan === 'anon') return "You've had your free Concierge question. Sign up free to keep going with 10 questions a month.";
  if (a.plan === 'free') return "You've used your " + a.limit + ' free Concierge questions this month. They reset on the 1st, or High Voltage gives you 50 a month.';
  return "You've used all " + a.limit + ' Concierge questions this month. They reset on the 1st.';
}
function LimitCard({ limit, compact }) {
  const a = limit && limit.allowance;
  const L = window.Usage ? Usage.links(a, 'concierge.html') : { primary: { href: SIGN_IN, label: 'Sign in' } };
  return (
    <div className="drop" style={compact ? { padding: '22px 18px', margin: '8px 0 0' } : null}>
      <h3>{!a || a.plan === 'anon' ? 'Sign up free to keep going' : "You've used this month's questions"}</h3>
      <p>{(limit && limit.message) || spentText(a)}</p>
      <div className="acts">
        {L.primary && <a className="btn btn-accent" href={L.primary.href}>{L.primary.label} <span className="arr">→</span></a>}
        {L.secondary && <a className="btn" href={L.secondary.href}>{L.secondary.label}</a>}
      </div>
    </div>
  );
}

function Gate({ auth, note, limit }) {
  if (limit) return <LimitCard limit={limit}/>;
  if (auth === 'checking') {
    return (
      <div className="drop" aria-busy="true">
        <span className="skel" style={{ width: '38%', height: '20px', margin: '0 auto' }}/>
        <span className="skel" style={{ width: '62%', margin: '14px auto 0' }}/>
      </div>
    );
  }
  if (auth === 'unavailable') {
    return (
      <div className="drop">
        <h3>The Concierge is unavailable</h3>
        <p>We can't check sign-ins right now. This is on our side — please try again shortly.</p>
        <div className="acts"><button className="btn btn-accent" onClick={() => location.reload()}>Try again</button></div>
      </div>
    );
  }
  return (
    <div className="drop">
      <h3>Sign in to use the Concierge</h3>
      <p>{note || 'The Concierge comes with an ICE → EV account. Sign in to ask about cars, charging, running costs, servicing, parts or buying, with answers that can use your own car and charge log.'}</p>
      <div className="acts">
        <a className="btn btn-accent" href={SIGN_IN}>Sign in <span className="arr">→</span></a>
      </div>
      <div className="hint">New here? You can create an account on the next page.</div>
    </div>
  );
}

const WELCOME = {
  role: 'assistant',
  content: "Hi — I'm the ICE → EV Concierge. Ask me about electric or petrol cars, charging, running costs, servicing, parts, or buying new or pre-owned. If you'd like a dealer, workshop or parts supplier to help, I can arrange that too — only with your say-so.",
};

function App() {
  // checking | in | out | unavailable
  const [auth, setAuth] = useState('checking');
  const [uid, setUid] = useState(null);
  const [gateNote, setGateNote] = useState('');
  const [conv, setConv] = useState(null);
  const [msgs, setMsgs] = useState([WELCOME]);
  const [lead, setLead] = useState(null);
  const [consentReq, setConsentReq] = useState(null);
  const [typing, setTyping] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);           // { text, retry }
  const [val, setVal] = useState('');
  const [rated, setRated] = useState({});
  const [restoring, setRestoring] = useState(false);
  const [member, setMember] = useState(null);          // { signed_in, member } once known
  const [personal, setPersonal] = useState(personalPref);
  const endRef = useRef(null);
  const taRef = useRef(null);

  useEffect(() => { endRef.current && endRef.current.scrollIntoView({ behavior: 'smooth', block: 'end' }); }, [msgs, typing, consentReq, error]);

  // Who is signed in, and follow it: signing out in another tab, or the
  // session ending, closes the chat here as well.
  useEffect(() => {
    if (!window.DB || !DB.configured) { setAuth('unavailable'); return; }
    let alive = true;
    const set = (u) => { if (!alive) return; setUid(u ? u.id : null); setAuth(u ? 'in' : 'out'); };
    DB.getUser().then(set).catch(() => alive && setAuth('unavailable'));
    const sub = DB.sb.auth.onAuthStateChange((_evt, session) => set(session && session.user));
    return () => {
      alive = false;
      try { sub.data.subscription.unsubscribe(); } catch (ex) { /* nothing to undo */ }
    };
  }, []);

  const expired = () => { setGateNote(EXPIRED); setAuth('out'); };

  // The question allowance: visitors get one, members their monthly allowance.
  const [quota, setQuota] = useState(null);
  const [limit, setLimit] = useState(null);       // { message, allowance } once refused
  useEffect(() => {
    setLimit(null); setQuota(null);
    if ((auth !== 'out' && auth !== 'in') || !window.Usage) return;
    let alive = true;
    Usage.me(true).then((d) => { if (alive) setQuota(d.allowances.concierge); })
      .catch(() => alive && auth === 'out' && setQuota({ ok: false, plan: 'anon', tool: 'concierge' }));
    return () => { alive = false; };
  }, [auth]);
  const open = auth === 'in' || (auth === 'out' && quota && quota.ok);
  const spent = !!limit || (quota && quota.limit != null && quota.remaining === 0);

  // Whenever the member changes, drop whatever chat was showing and pick up
  // where this one left off. "me" drives the personalised line and the starters.
  useEffect(() => {
    setConv(null); setMsgs([WELCOME]); setLead(null); setConsentReq(null); setError(null); setRated({}); setMember(null);
    if (!uid) return;
    let alive = true;
    call({ action: 'me' }).then((m) => alive && setMember(m)).catch(() => alive && setMember({ signed_in: false }));
    const c = load(uid);
    if (!c) { setRestoring(false); return () => { alive = false; }; }
    setConv(c); setRestoring(true);
    call({ action: 'history', conversation_id: c.id, token: c.token })
      .then((h) => {
        if (!alive) return;
        if (h.messages.length) setMsgs([WELCOME, ...h.messages]);
        setLead(h.lead);
        setConsentReq(h.consent_request);
      })
      .catch((e) => {
        if (!alive) return;
        if (e.status === 401) { expired(); return; }   // keep the chat for when they sign back in
        save(uid, null); setConv(null);
      })
      .finally(() => alive && setRestoring(false));
    return () => { alive = false; };
  }, [uid]);

  const togglePersonal = () => {
    const next = !personal;
    setPersonal(next);
    try { localStorage.setItem(PKEY, next ? 'on' : 'off'); } catch (e) {}
  };

  const ensureConv = async () => {
    if (conv) return conv;
    const r = await call({ action: 'start' });
    const c = { id: r.conversation.id, token: r.token };
    save(uid, c); setConv(c);
    return c;
  };

  const send = useCallback(async (text) => {
    const q = String(text || '').trim();
    if (!q || busy) return;
    setError(null); setBusy(true); setVal('');
    if (taRef.current) taRef.current.style.height = 'auto';
    const temp = { role: 'user', content: q, tempId: Date.now() };
    setMsgs((m) => [...m, temp]);
    setTyping(true);
    try {
      const c = await ensureConv();
      const r = await call({ action: 'message', conversation_id: c.id, token: c.token, text: q, personalise: personal });
      setMsgs((m) => [...m, r.message]);
      if (r.lead) setLead(r.lead);
      setConsentReq(r.consent_request || null);
      if (r.allowance) setQuota(r.allowance);
    } catch (e) {
      // The session ended between opening the page and asking.
      if (e.status === 401) { setMsgs((m) => m.filter((x) => x !== temp)); expired(); return; }
      // Out of questions: say so where the box was, and keep their text.
      if (e.code === 'limit_reached') { setMsgs((m) => m.filter((x) => x !== temp)); setVal(q); setLimit({ message: e.message, allowance: e.allowance }); return; }
      if (e.status === 404 || e.status === 410) { save(uid, null); setConv(null); }
      setError({ text: e.message, retry: e.status !== 400 ? q : null });
      if (e.status === 400) setMsgs((m) => m.filter((x) => x !== temp));
    } finally {
      setTyping(false); setBusy(false);
    }
  }, [busy, conv, personal, uid, auth]);

  const retry = () => {
    if (!error || !error.retry) return;
    const q = error.retry;
    setMsgs((m) => { const i = m.map((x) => x.content).lastIndexOf(q); return i >= 0 ? [...m.slice(0, i), ...m.slice(i + 1)] : m; });
    send(q);
  };

  const decide = async (decision) => {
    if (!lead || !conv) return;
    setBusy(true); setError(null);
    try {
      const r = await call({ action: 'consent', conversation_id: conv.id, token: conv.token, lead_id: lead.id, decision });
      setLead(r.lead);
      setConsentReq(null);
      const h = await call({ action: 'history', conversation_id: conv.id, token: conv.token });
      setMsgs([WELCOME, ...h.messages]);
      if (decision === 'decline') setMsgs((m) => [...m, { role: 'system', content: "No problem — nothing has been shared. Ask me anything else, or say if you change your mind." }]);
    } catch (e) {
      if (e.status === 401) { expired(); return; }
      setError({ text: e.message });
    } finally { setBusy(false); }
  };

  const feedback = async (id, rating) => {
    if (!conv) return;
    setRated((r) => ({ ...r, [id]: rating }));
    try { await call({ action: 'feedback', conversation_id: conv.id, token: conv.token, message_id: id, rating }); }
    catch (e) { setRated((r) => { const c = { ...r }; delete c[id]; return c; }); }
  };

  const reset = () => {
    save(uid, null); setConv(null); setMsgs([WELCOME]); setLead(null); setConsentReq(null); setError(null); setRated({});
  };

  const grow = () => { const t = taRef.current; if (t) { t.style.height = 'auto'; t.style.height = Math.min(t.scrollHeight, 160) + 'px'; } };
  const asked = msgs.some((m) => m.role === 'user');
  const mem = member && member.member;
  const starters = mem && personal && mem.sessions > 0 ? [...PERSONAL_STARTERS, ...STARTERS.slice(0, 2)] : STARTERS;
  const personalLine = !member ? null : !member.signed_in
    ? <><span className="d off"/><a href={'auth.html?next=' + encodeURIComponent('concierge.html')}>Sign in</a>&nbsp;for answers based on your car and charging</>
    : <><span className={'d' + (personal ? '' : ' off')}/>{personal
        ? <>Personal for <b>{mem && mem.first_name ? mem.first_name : 'you'}</b>{mem && mem.car ? <> · {mem.car}</> : ''} · {mem && mem.sessions ? <a href="charge-log.html">{mem.sessions} charging session{mem.sessions === 1 ? '' : 's'}</a> : <a href="charge-log.html">no charge log yet</a>}</>
        : <>Personal answers off</>}
        <button className="pswitch" onClick={togglePersonal} aria-pressed={personal}>{personal ? 'Turn off' : 'Turn on'}</button></>;

  return (
    <div className="chat-page">
      <div className="chat-col">
        <div className="chat-head">
          <div className="eyebrow" style={{ justifyContent: 'center' }}>Concierge <span className="pp">AI</span></div>
          <h1>Ask anything about your car.</h1>
          <div className="ground"><span className="d"/>Answers from <b>ICE → EV approved sources</b> · not a mechanical diagnosis</div>
          {auth === 'in' && personalLine && <div className="ground personal">{personalLine}</div>}
          {open && !spent && window.Usage && Usage.note(quota) && <div className="ground">{Usage.note(quota)}</div>}
        </div>

        {!open ? <Gate auth={auth === 'out' && !quota ? 'checking' : auth} note={gateNote}
            limit={auth === 'out' && quota && !quota.ok ? { allowance: quota, message: quota.message } : null}/> : <>

        <div className="thread" aria-live="polite">
          {restoring && <div className="sysmsg">Loading your conversation…</div>}
          {msgs.map((m, i) => <Message key={m.id || m.tempId || i} m={m} onFeedback={feedback} rated={rated[m.id]} />)}
          {typing && (
            <div className="msg ai">
              <div className="avatar ai"><Spark/></div>
              <div className="bubble"><div className="typing" aria-label="Concierge is typing"><i/><i/><i/></div></div>
            </div>
          )}
          {consentReq && !typing && <ConsentCard req={consentReq} busy={busy} onDecide={decide} />}
          {error && (
            <div className="errmsg" role="alert">{error.text}{error.retry && <button onClick={retry}>Try again</button>}</div>
          )}
          <div ref={endRef} style={{ scrollMarginBottom: 240 }} />
        </div>

        <div className="composer">
          <div className="toolbar">
            {lead && lead.consent_status === 'granted'
              ? <span className="sharing">Sharing details for {lead.ref} · <button disabled={busy} onClick={() => { if (confirm('Withdraw consent? We will stop sharing and ask any business that received your details to delete them.')) decide('withdraw'); }}>Withdraw</button></span>
              : <span/>}
            {asked && <button className="newchat" onClick={reset}>Start a new chat</button>}
          </div>
          {spent ? <LimitCard limit={limit || { allowance: quota }} compact/> : <>
          {!asked && !restoring && (
            <div className="chips">
              {starters.map((q) => <span className="chip" key={q} role="button" tabIndex={0} onClick={() => send(q)} onKeyDown={(e) => { if (e.key === 'Enter') send(q); }}>{q}</span>)}
            </div>
          )}
          <form className="inputbar" onSubmit={(e) => { e.preventDefault(); send(val); }}>
            <textarea ref={taRef} rows={1} value={val} maxLength={2000} disabled={restoring}
              onChange={(e) => { setVal(e.target.value); grow(); }}
              onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(val); } }}
              placeholder="Ask about charging, running costs, a service, parts, or buying…" aria-label="Your message" />
            <button className="sendbtn" type="submit" disabled={!val.trim() || busy} aria-label="Send">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </button>
          </form>
          </>}
          <div className="fine">
            Please don't share ID numbers or banking details. We share your details with a business only if you say yes.<br/>
            {member && member.signed_in && personal && <>Personal answers send your first name, profile car, settings and charge-log figures (never your contact details) to our AI provider for this chat.<br/></>}
            Prefer a person? <a href="mailto:info@icetoev.co.za?subject=Concierge">info@icetoev.co.za</a>
          </div>
        </div>

        </>}
      </div>
    </div>
  );
}

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