/* Atlas Ledger — Messages page: conversational tasks (direction C, Harbour skin) */

function Bubble({ from, children, time }) {
  const mine = from === 'me';
  return (
    <div style={{
      maxWidth: '78%', alignSelf: mine ? 'flex-end' : 'flex-start',
      background: mine ? 'var(--hb-teal)' : '#fff',
      color: mine ? '#fff' : 'var(--hb-ink)',
      border: mine ? 'none' : '1px solid var(--hb-line)',
      borderRadius: mine ? '14px 4px 14px 14px' : '4px 14px 14px 14px',
      padding: '10px 14px', fontSize: 13.5, lineHeight: 1.55,
    }}>
      {children}
      {time && <div style={{ fontSize: 10, color: mine ? 'rgba(255,255,255,.65)' : 'var(--hb-faint)', textAlign: mine ? 'right' : 'left', marginTop: 4 }}>{time}{mine ? ' ✓✓' : ''}</div>}
    </div>
  );
}

function MessagesPage({ state, setState, go }) {
  const { answers, confirmed } = state;
  const threadEnd = React.useRef(null);
  const [draft, setDraft] = React.useState('');
  const [sent, setSent] = React.useState([]);

  const answerViaChat = (val) => {
    setState((s) => ({ ...s, answers: { ...s.answers, q1: val } }));
  };
  const send = () => {
    if (!draft.trim()) return;
    setSent((arr) => [...arr, draft.trim()]);
    setDraft('');
  };

  return (
    <div className="hb-page" style={{ width: 'min(620px, calc(100vw - 40px))', margin: '0 auto', paddingTop: 20, paddingBottom: 20, display: 'flex', flexDirection: 'column', height: 'calc(100vh - 62px)', boxSizing: 'border-box' }}>
      {/* thread header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, paddingBottom: 14, borderBottom: '1px solid var(--hb-line)' }}>
        <div style={{ width: 38, height: 38, borderRadius: '50%', background: 'var(--hb-teal-tint)', color: 'var(--hb-teal-deep)', fontWeight: 700, fontSize: 13, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>AL</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 700 }}>Your accounting team</div>
          <div style={{ fontSize: 11.5, color: 'var(--hb-muted)' }}>Replies within the hour · also on WhatsApp</div>
        </div>
        <button className="hb-btn ghost" style={{ padding: '8px 14px', fontSize: 12.5, whiteSpace: 'nowrap', flexShrink: 0 }}>
          <HIcon name="whatsapp" size={15} color="var(--hb-teal)" /> WhatsApp
        </button>
      </div>

      {/* thread */}
      <div className="hb-thread" style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 10, padding: '16px 2px' }}>
        <div style={{ alignSelf: 'center', background: '#E7ECF1', borderRadius: 8, padding: '3px 10px', fontSize: 11, color: 'var(--hb-muted)' }}>Today</div>

        <Bubble from="team" time="09:42">
          We found a transfer of <b className="hb-num">HKD 52,000</b> to WK Logistics on 15 May with no matching document — what was it for?
        </Bubble>

        {!answers.q1 ? (
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {['Logistics cost · suggested', 'Supplier payment', 'Upload receipt'].map((c, i) => (
              <button key={c} onClick={() => answerViaChat(c.split(' ·')[0])} style={{
                border: '1px solid var(--hb-teal)', background: '#fff', borderRadius: 999, padding: '8px 14px',
                fontSize: 12.5, color: 'var(--hb-teal-deep)', fontWeight: i === 0 ? 700 : 500, cursor: 'pointer', fontFamily: 'var(--hb-grot)',
                whiteSpace: 'nowrap', flexShrink: 0,
              }}>{c}</button>
            ))}
          </div>
        ) : (
          <React.Fragment>
            <Bubble from="me" time="09:47">{answers.q1} — WK handles our shipping</Bubble>
            <Bubble from="team" time="09:48">
              Got it ✓ Booked to <b>5102 Logistics</b>. Future WK Logistics payments will be matched automatically.
            </Bubble>
          </React.Fragment>
        )}

        <Bubble from="team" time="09:48">
          Your May accounts {confirmed ? 'are confirmed ✓ Thank you!' : 'are nearly ready —'}
          {!confirmed && (
            <div style={{ background: 'var(--hb-bg)', borderRadius: 10, padding: '11px 13px', marginTop: 8 }}>
              {[['Revenue', '380,000'], ['Net profit', '95,000'], ['Closing cash', '1,245,300']].map(([l, v]) => (
                <div key={l} style={{ display: 'flex', justifyContent: 'space-between', padding: '3.5px 0' }}>
                  <span style={{ color: 'var(--hb-muted)', fontSize: 12 }}>{l}</span>
                  <span className="hb-num" style={{ fontSize: 12.5, fontWeight: 600 }}>{v}</span>
                </div>
              ))}
              <button className="hb-btn" onClick={() => go('tasks')} style={{ width: '100%', height: 40, fontSize: 13.5, marginTop: 8 }}>Finish the close →</button>
            </div>
          )}
        </Bubble>

        {sent.map((m, i) => <Bubble key={'s' + i} from="me" time="now">{m}</Bubble>)}
        {sent.length > 0 && (
          <Bubble from="team" time="now">Thanks — someone from your team will reply within the hour.</Bubble>
        )}
        <div ref={threadEnd}></div>
      </div>

      {/* input */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingTop: 12, borderTop: '1px solid var(--hb-line)' }}>
        <HIcon name="clip" size={19} color="var(--hb-muted)" />
        <input
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && send()}
          placeholder="Message your accounting team…"
          style={{ flex: 1, height: 42, borderRadius: 999, border: '1px solid var(--hb-line)', padding: '0 16px', fontSize: 13.5, fontFamily: 'var(--hb-grot)', outline: 'none', background: '#fff' }}
        />
        <button onClick={send} style={{ width: 40, height: 40, borderRadius: '50%', background: 'var(--hb-teal)', border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
          <HIcon name="send" size={17} color="#fff" />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { MessagesPage });
