// Composer.jsx — full-screen social composer overlay.
// Same layout/visuals as the design kit. The local "fake transform"
// functions for AI rewrite are replaced with real calls to
// POST /rewrite (server-side Claude call, brand-voice aware).
// Posting itself (onPostAll) is still owned by the parent page, which now
// calls the real backend instead of a setTimeout simulation.
const CHANNELS = [
  { key: 'facebook', label: 'Facebook', icon: 'facebook' },
  { key: 'instagram', label: 'Instagram', icon: 'instagram' },
  { key: 'x', label: 'X', icon: 'twitter' },
  { key: 'linkedin', label: 'LinkedIn', icon: 'linkedin' },
];

const LIMITS = { facebook: 2200, instagram: 2200, x: 280, linkedin: 3000 };

const PRESETS = [
  { key: 'shorter', label: 'Shorter', icon: 'minimize-2' },
  { key: 'punchier', label: 'Punchier', icon: 'zap' },
  { key: 'emoji', label: 'Add emoji', icon: 'smile' },
  { key: 'hashtags', label: 'Add hashtags', icon: 'hash' },
  { key: 'formal', label: 'More formal', icon: 'briefcase' },
];

function Composer({ open, queue, index, setIndex, onClose, onPostAll, account, generating, posted, voice }) {
  const promo = queue[index];

  // message state lives per-promo-per-channel: { [promoId]: { base, overrides: {ch: text} } }
  const [msgState, setMsgState] = React.useState({});
  const [channels, setChannels] = React.useState(['facebook', 'instagram']);
  const [activeChannel, setActiveChannel] = React.useState('facebook');
  const [editChannel, setEditChannel] = React.useState('all');
  const [aiPrompt, setAiPrompt] = React.useState('');
  const [aiThinking, setAiThinking] = React.useState(false);
  const [aiError, setAiError] = React.useState(null);
  const [schedule, setSchedule] = React.useState({ mode: 'now', date: '', time: '10:30' });

  // seed message state when promo changes — if the operator hasn't supplied
  // social copy, auto-generate an opening draft via AI rather than starting blank.
  React.useEffect(() => {
    if (!promo) return;
    if (msgState[promo.id]) return;
    if (promo.social) {
      setMsgState((s) => ({ ...s, [promo.id]: { base: promo.social, overrides: {} } }));
      return;
    }
    setMsgState((s) => ({ ...s, [promo.id]: { base: '', overrides: {} } }));
    (async () => {
      setAiThinking(true);
      try {
        const seedText = `${promo.title} — ${promo.operator}, ${promo.destination}.`;
        const { text } = await window.TMS_AUTH.apiFetch('/rewrite', {
          method: 'POST',
          body: JSON.stringify({
            text: seedText,
            customPrompt: 'Write an opening social post draft for this holiday offer — warm, inviting, end with a soft call to action.',
          }),
        });
        setMsgState((s) => ({ ...s, [promo.id]: { base: text, overrides: {} } }));
      } catch (e) {
        setAiError('Could not auto-draft a message — write one manually below.');
      } finally {
        setAiThinking(false);
      }
    })();
  }, [promo]);

  if (!open || !promo) return null;

  const pm = msgState[promo.id] || { base: '', overrides: {} };
  const effectiveMessage = (ch) => pm.overrides[ch] != null ? pm.overrides[ch] : pm.base;
  const currentMessage = editChannel === 'all' ? pm.base : effectiveMessage(editChannel);

  const setMessage = (text) => {
    setMsgState((s) => {
      const cur = s[promo.id] || { base: '', overrides: {} };
      if (editChannel === 'all') return { ...s, [promo.id]: { ...cur, base: text } };
      return { ...s, [promo.id]: { ...cur, overrides: { ...cur.overrides, [editChannel]: text } } };
    });
  };

  const limit = editChannel === 'all' ? 2200 : LIMITS[editChannel];

  const applyAi = async (opts) => {
    setAiError(null);
    setAiThinking(true);
    try {
      const { text } = await window.TMS_AUTH.apiFetch('/rewrite', {
        method: 'POST',
        body: JSON.stringify({
          text: currentMessage,
          channel: editChannel === 'all' ? null : editChannel,
          charLimit: limit,
          ...opts,
        }),
      });
      setMessage(text);
      setAiPrompt('');
    } catch (e) {
      setAiError(e.message || 'AI rewrite failed — try again.');
    } finally {
      setAiThinking(false);
    }
  };

  const over = currentMessage.length > limit;
  const stepNav = queue.length > 1;

  return (
    <div className="sp-modal-bg" onClick={onClose}>
      <div className="sp-modal" onClick={(e) => e.stopPropagation()}>
        <div className="sp-modal-head">
          <div className="sp-modal-head-left">
            <div className="sp-modal-thumb" style={{ backgroundImage: 'url(' + promo.image + ')' }}></div>
            <div style={{ minWidth: 0 }}>
              <h2>{promo.title}</h2>
              <div className="sub">{promo.operator} · {promo.destination} · ID {promo.id}</div>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            {stepNav && (
              <div className="sp-modal-nav">
                <button className="sp-icon-btn" disabled={index === 0} onClick={() => setIndex(Math.max(0, index - 1))} aria-label="Previous"><i data-lucide="chevron-left"></i></button>
                <span className="counter"><b>{index + 1}</b> of {queue.length}</span>
                <button className="sp-icon-btn" disabled={index >= queue.length - 1} onClick={() => setIndex(Math.min(queue.length - 1, index + 1))} aria-label="Next"><i data-lucide="chevron-right"></i></button>
              </div>
            )}
            <button className="sp-icon-btn" onClick={onClose} aria-label="Close"><i data-lucide="x"></i></button>
          </div>
        </div>

        <div className="sp-composer">
          {/* ---------- left ---------- */}
          <div className="sp-compose-left">
            <div className="sp-card">
              <div className="sp-card-head"><h3><i data-lucide="share-2"></i> Post to</h3></div>
              <div className="sp-channels">
                {CHANNELS.map((c) => {
                  const on = channels.includes(c.key);
                  return (
                    <button key={c.key} className={'sp-channel ' + (on ? 'is-on' : '')}
                      onClick={() => setChannels((cs) => cs.includes(c.key) ? cs.filter((x) => x !== c.key) : [...cs, c.key])}>
                      <span className={'sp-channel-ico ico-' + c.key}><i data-lucide={c.icon}></i></span>
                      {c.label}
                      <span className="check"><i data-lucide="check"></i></span>
                    </button>
                  );
                })}
              </div>
            </div>

            <div className="sp-card">
              <div className="sp-card-head">
                <h3><i data-lucide="pencil"></i> Message</h3>
                <span style={{ font: '500 12px/1 var(--font-body)', color: 'var(--hub-muted)' }}>
                  {editChannel === 'all' ? 'All channels' : 'Override for ' + channelName(editChannel)}
                </span>
              </div>
              <div className="sp-msg-tabs">
                <button className={'sp-msg-tab ' + (editChannel === 'all' ? 'is-on' : '')} onClick={() => setEditChannel('all')}>All</button>
                {channels.map((ch) => (
                  <button key={ch} className={'sp-msg-tab ' + (editChannel === ch ? 'is-on' : '') + (pm.overrides[ch] != null ? ' override' : '')} onClick={() => setEditChannel(ch)}>
                    <span className={'dot ico-' + ch}></span> {channelName(ch)}
                  </button>
                ))}
              </div>
              <textarea className="sp-textarea" value={currentMessage} onChange={(e) => setMessage(e.target.value)} placeholder={aiThinking ? 'Drafting an opening message…' : ''} />
              <div className="sp-msg-meta">
                <span className={over ? 'over' : ''}>{currentMessage.length} / {limit} chars</span>
                {editChannel !== 'all' && pm.overrides[editChannel] != null && (
                  <button className="sp-link" style={{ background: 'transparent', border: 0, color: 'var(--hub-teal)', font: '600 12px/1 var(--font-display)', cursor: 'pointer' }}
                    onClick={() => setMsgState((s) => { const cur = { ...s[promo.id] }; const ov = { ...cur.overrides }; delete ov[editChannel]; return { ...s, [promo.id]: { ...cur, overrides: ov } }; })}>
                    Reset to shared message
                  </button>
                )}
              </div>

              <div className="sp-ai" style={{ marginTop: 14 }}>
                <div className="sp-ai-head">
                  <span className="badge"><i data-lucide="sparkles"></i> Rewrite with AI</span>
                  {voice?.tone ? (
                    <span className="brandtag"><i data-lucide="check-circle-2"></i> your brand voice applied</span>
                  ) : (
                    <a className="brandtag" href="/social/brand-voice"><i data-lucide="sparkles"></i> using default voice — set yours →</a>
                  )}
                </div>
                <div className="sp-ai-presets">
                  {PRESETS.map((p) => (
                    <button key={p.key} className="sp-preset" disabled={aiThinking} onClick={() => applyAi({ preset: p.key })}>
                      <i data-lucide={p.icon}></i> {p.label}
                    </button>
                  ))}
                </div>
                <div className="sp-ai-prompt">
                  <textarea value={aiPrompt} onChange={(e) => setAiPrompt(e.target.value)}
                    placeholder="Or tell the AI what to do — e.g. 'make it about a family half-term getaway, mention 0% deposit'…" />
                  <button className="sp-ai-send" disabled={!aiPrompt.trim() || aiThinking}
                    onClick={() => applyAi({ customPrompt: aiPrompt.trim() })}>
                    <i data-lucide="arrow-up"></i>
                  </button>
                </div>
                {aiThinking && <div className="sp-ai-thinking"><i data-lucide="loader-2" className="is-spin"></i> Rewriting in your brand voice…</div>}
                {aiError && <div className="sp-ai-thinking" style={{ color: 'var(--tms-danger, #c0392b)' }}><i data-lucide="alert-circle"></i> {aiError}</div>}
              </div>
            </div>

            <div className="sp-card">
              <div className="sp-card-head"><h3><i data-lucide="calendar-clock"></i> When to post</h3></div>
              <div className="sp-sched-tabs">
                <button className={schedule.mode === 'now' ? 'is-on' : ''} onClick={() => setSchedule({ ...schedule, mode: 'now' })}><i data-lucide="send"></i> Post now</button>
                <button className={schedule.mode === 'schedule' ? 'is-on' : ''} onClick={() => setSchedule({ ...schedule, mode: 'schedule' })}><i data-lucide="calendar"></i> Schedule</button>
              </div>
              {schedule.mode === 'schedule' && (
                <div className="sp-sched-fields">
                  <div className="sp-filter"><label>Date</label><input type="date" value={schedule.date} onChange={(e) => setSchedule({ ...schedule, date: e.target.value })} /></div>
                  <div className="sp-filter"><label>Time</label><input type="time" value={schedule.time} onChange={(e) => setSchedule({ ...schedule, time: e.target.value })} /></div>
                  <div className="sp-besttime">
                    <i data-lucide="trending-up"></i>
                    <span>Most agents see the best engagement on weekday mornings, 9–11am.</span>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* ---------- right (preview) ---------- */}
          <div className="sp-compose-right">
            <div className="sp-preview-head">
              <h3>Preview</h3>
              <div className="sp-preview-switch">
                {channels.map((ch) => {
                  const c = CHANNELS.find((x) => x.key === ch);
                  return (
                    <button key={ch} className={activeChannel === ch ? 'is-on' : ''} onClick={() => setActiveChannel(ch)} aria-label={channelName(ch)}>
                      <span className={'sp-channel-ico ico-' + ch}><i data-lucide={c.icon}></i></span>
                    </button>
                  );
                })}
              </div>
            </div>

            {channels.length === 0 ? (
              <div style={{ padding: 40, textAlign: 'center', color: 'var(--hub-muted)', fontSize: 14 }}>
                Select at least one channel to preview.
              </div>
            ) : (
              <SocialPreview
                channel={channels.includes(activeChannel) ? activeChannel : channels[0]}
                message={effectiveMessage(channels.includes(activeChannel) ? activeChannel : channels[0])}
                promo={promo}
                account={account}
              />
            )}

            <div className="sp-compose-foot">
              <div className="sp-summary">
                <i data-lucide={schedule.mode === 'now' ? 'send' : 'calendar-clock'}></i>
                <span>
                  {channels.length} channel{channels.length === 1 ? '' : 's'} ·{' '}
                  {schedule.mode === 'now' ? 'posting immediately' : 'scheduled ' + (schedule.date || '(pick a date)') + ' ' + schedule.time}
                  {queue.length > 1 ? ' · ' + queue.length + ' promotions in queue' : ''}
                </span>
              </div>
              <button className="sp-btn sp-btn--orange sp-btn--lg sp-btn--block"
                disabled={channels.length === 0 || generating || (schedule.mode === 'schedule' && !schedule.date)}
                onClick={() => onPostAll(schedule, channels, msgState)}>
                {generating ? (<><i data-lucide="loader-2" className="is-spin"></i> Sending to Metricool…</>)
                  : posted ? (<><i data-lucide="check"></i> Done</>)
                  : schedule.mode === 'now'
                    ? (<><i data-lucide="send"></i> Post {queue.length > 1 ? 'all ' + queue.length : 'now'}</>)
                    : (<><i data-lucide="calendar-clock"></i> Schedule {queue.length > 1 ? 'all ' + queue.length : 'post'}</>)}
              </button>
              <div style={{ textAlign: 'center', font: '400 11.5px/1.4 var(--font-body)', color: 'var(--hub-soft)' }}>
                Published via your connected Metricool account
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
window.Composer = Composer;
