/* screen-creator-campaign-actions.jsx — Interactive prototypes for actions in the
   My Campaign flow. Each action that didn't have a click target now opens a
   modal / drawer / popover / toast so the full demo runs end-to-end.

   Exposes:
     useCampaignActions()  → hook that returns {openMessage, openShipment, openBriefPdf,
                              openAISuggest, openTimePicker, toast}
     <CampaignActionsHost /> → renders all overlays controlled by the hook
*/
/* global React, Modal, Drawer, Popover, Toast, Avatar, Pill, Icon */

// ── 1. Message Trang modal ─────────────────────────────────────────
function MessageTrangModal({ open, onClose, prefill = '' }) {
  const [draft, setDraft] = React.useState(prefill);
  const [thread, setThread] = React.useState([
    { who: 'Trang', txt: 'Hey Linh! Excited to have you on this one 🍊', when: 'Yesterday', c: '#FF6FA3' },
    { who: 'You',   txt: 'Same! Reading through the brief now.', when: 'Yesterday', c: '#009CFF' },
  ]);
  const [typing, setTyping] = React.useState(false);

  React.useEffect(() => { if (open) setDraft(prefill); }, [open, prefill]);

  const send = () => {
    const txt = draft.trim();
    if (!txt) return;
    setThread(t => [...t, { who: 'You', txt, when: 'now', c: '#009CFF' }]);
    setDraft('');
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setThread(t => [...t, { who: 'Trang', txt: 'Got it — will reply within the hour 🙌', when: 'now', c: '#FF6FA3' }]);
    }, 1400);
  };

  return (
    <Modal open={open} onClose={onClose} width={520}
      title="Message Trang Lê"
      subtitle="Head of Brand · Coolmate · usually replies within 4h">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, maxHeight: 360, overflowY: 'auto', padding: '4px 0' }}>
        {thread.map((m, i) => (
          <div key={i} className="row items-start gap-8" style={{
            flexDirection: m.who === 'You' ? 'row-reverse' : 'row',
            animation: i >= 2 ? 'cardIn .3s ease-out' : 'none'
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: 999, flexShrink: 0,
              background: m.c, color: 'white', display: 'grid', placeItems: 'center',
              fontWeight: 800, fontSize: 11
            }}>{m.who === 'You' ? 'Y' : 'T'}</div>
            <div style={{
              padding: '8px 12px', borderRadius: 12, maxWidth: '78%',
              background: m.who === 'You' ? 'var(--ink)' : 'var(--bg-soft)',
              color: m.who === 'You' ? 'white' : 'var(--ink)'
            }}>
              <div style={{ fontSize: 12.5, lineHeight: 1.4 }}>{m.txt}</div>
              <div style={{ fontSize: 10, opacity: 0.6, marginTop: 2 }}>{m.when}</div>
            </div>
          </div>
        ))}
        {typing && (
          <div className="row items-center gap-8">
            <div style={{ width: 28, height: 28, borderRadius: 999, background: '#FF6FA3', color: 'white', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 11 }}>T</div>
            <div style={{ padding: '10px 14px', borderRadius: 12, background: 'var(--bg-soft)' }}>
              <span style={{ display: 'inline-flex', gap: 3 }}>
                {[0, 1, 2].map(i => (
                  <span key={i} style={{
                    width: 6, height: 6, borderRadius: 999, background: 'var(--ink-soft)',
                    animation: `bounce 1.4s ${i * 0.16}s infinite`
                  }} />
                ))}
              </span>
            </div>
          </div>
        )}
      </div>
      <div className="row items-center gap-8 mt-4" style={{ padding: '8px 12px', background: 'var(--bg-soft)', borderRadius: 999 }}>
        <input placeholder="Write a message..."
          value={draft}
          onChange={e => setDraft(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') send(); }}
          style={{ flex: 1, border: 0, background: 'transparent', fontSize: 13, outline: 'none', fontFamily: 'inherit' }} />
        <button onClick={send} disabled={!draft.trim()}
          className="btn btn-primary btn-sm"
          style={{ opacity: draft.trim() ? 1 : 0.4, cursor: draft.trim() ? 'pointer' : 'not-allowed' }}>
          Send {Icon.arrow}
        </button>
      </div>
      <style>{`@keyframes bounce { 0%, 60%, 100% { transform: translateY(0); } 30% { transform: translateY(-4px); } }`}</style>
    </Modal>
  );
}

// ── 2. Shipment tracking drawer ────────────────────────────────────
function ShipmentDrawer({ open, onClose }) {
  const events = [
    { t: 'Picked up at warehouse', when: 'May 16 · 09:24', loc: 'GHN Hub · HCM District 7', state: 'done' },
    { t: 'Out for shipping',        when: 'May 16 · 14:10', loc: 'GHN sorting center',      state: 'done' },
    { t: 'In transit to your city', when: 'May 17 · 06:55', loc: 'Highway 1A',              state: 'active' },
    { t: 'Out for delivery',        when: 'Expected May 19', loc: 'GHN HCM District 3',     state: 'pending' },
    { t: 'Delivered',               when: 'Expected May 19', loc: '143 Pasteur, District 1', state: 'pending' },
  ];
  return (
    <Drawer open={open} onClose={onClose} width={460}>
      <div style={{ padding: 24 }}>
        <div className="row items-center justify-between mb-4">
          <div className="title-lg">Track your kit</div>
          <button onClick={onClose} className="btn-sm" style={{ background: 'transparent', border: 0, fontSize: 20, cursor: 'pointer', color: 'var(--ink-soft)' }}>×</button>
        </div>

        <div className="card-elevated" style={{ padding: 16, background: 'rgba(254,233,96,0.18)', border: '1px solid rgba(242,196,17,0.3)' }}>
          <div className="row items-center gap-12">
            <div style={{ fontSize: 32 }}>📦</div>
            <div className="flex-1">
              <div className="cap-label" style={{ fontSize: 9 }}>Tracking GHN · CLM-VC-20260516</div>
              <div className="bold" style={{ fontSize: 14 }}>Coolmate Vit-C kit + samples</div>
              <div className="muted" style={{ fontSize: 12 }}>3 items · 1.2kg · expected May 19</div>
            </div>
          </div>
        </div>

        <div className="cap-label mt-6 mb-3">Progress</div>
        <div style={{ position: 'relative' }}>
          <div style={{ position: 'absolute', left: 13, top: 8, bottom: 8, width: 2, background: 'var(--bg-soft)' }} />
          {events.map((e, i) => (
            <div key={i} className="row items-start gap-12" style={{ position: 'relative', padding: '10px 0' }}>
              <div style={{
                width: 28, height: 28, borderRadius: 999, flexShrink: 0, zIndex: 1,
                background: e.state === 'done' ? 'var(--mint-deep)' : e.state === 'active' ? 'var(--yellow)' : 'white',
                border: '3px solid var(--bg-canvas)',
                display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 11,
                color: e.state === 'done' ? 'white' : 'var(--ink)'
              }}>
                {e.state === 'done' ? '✓' : e.state === 'active' ? <span style={{ width: 8, height: 8, borderRadius: 999, background: 'currentColor', animation: 'pulse 1.5s infinite' }} /> : i + 1}
              </div>
              <div className="flex-1" style={{ paddingTop: 4 }}>
                <div className="bold" style={{ fontSize: 13, color: e.state === 'pending' ? 'var(--ink-soft)' : 'var(--ink)' }}>{e.t}</div>
                <div className="muted" style={{ fontSize: 11 }}>{e.when} · {e.loc}</div>
              </div>
            </div>
          ))}
        </div>

        <div className="row gap-8 mt-6">
          <button className="btn btn-ghost btn-sm" style={{ flex: 1 }}>{Icon.external} Open in GHN app</button>
          <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={onClose}>Got it</button>
        </div>
      </div>
    </Drawer>
  );
}

// ── 3. Brief PDF preview modal ─────────────────────────────────────
function BriefPdfModal({ open, onClose, onDownloaded }) {
  return (
    <Modal open={open} onClose={onClose} width={720}
      title="Brief · Vitamin C Skin Glow"
      subtitle="Coolmate · 28-day program · v1.2"
      footer={
        <div className="row gap-8">
          <button onClick={onClose} className="btn btn-ghost btn-sm">Close</button>
          <button onClick={() => { onDownloaded?.(); onClose(); }} className="btn btn-primary btn-sm">{Icon.external} Download PDF</button>
        </div>
      }>
      <div style={{ maxHeight: 480, overflowY: 'auto', padding: '4px 2px' }}>
        <div style={{
          background: 'white', border: '1px solid var(--line)', borderRadius: 8,
          padding: '32px 36px', fontFamily: 'Georgia, serif', color: 'var(--ink)', lineHeight: 1.6
        }}>
          <div style={{ borderBottom: '2px solid var(--ink)', paddingBottom: 12, marginBottom: 18 }}>
            <div style={{ fontSize: 10, letterSpacing: '0.16em', fontWeight: 700, color: 'var(--ink-soft)' }}>COOLMATE × PRIME INFLUENCER</div>
            <div style={{ fontSize: 28, fontWeight: 700, marginTop: 4, fontFamily: 'Space Grotesk' }}>Vitamin C Skin Glow</div>
            <div style={{ fontSize: 13, color: 'var(--ink-soft)' }}>28-day creator program · May 15 – Jun 11, 2026</div>
          </div>

          <h3 style={{ fontFamily: 'Space Grotesk', fontSize: 16, marginTop: 0 }}>1. The story we're telling</h3>
          <p style={{ fontSize: 13.5, margin: '4px 0 18px' }}>
            Vitamin C works — but most Gen-Z skincare audiences don't know why. We want creators to break down
            the ingredient science in plain language, then show a real 14-day routine. No miracle claims; honest
            voice, real lighting, and one "aha" moment per post.
          </p>

          <h3 style={{ fontFamily: 'Space Grotesk', fontSize: 16 }}>2. Deliverables</h3>
          <ul style={{ fontSize: 13.5, margin: '4px 0 18px', paddingLeft: 20 }}>
            <li><b>D1 · Concept &amp; script</b> — outline + caption draft. Due May 18.</li>
            <li><b>D2 · TikTok 30s</b> — first video, before/after pacing. Due May 22.</li>
            <li><b>D3 · Follow-up reel</b> — 14-day check-in across IG Reels. Due Jun 04.</li>
          </ul>

          <h3 style={{ fontFamily: 'Space Grotesk', fontSize: 16 }}>3. Mandatories</h3>
          <ul style={{ fontSize: 13.5, margin: '4px 0 18px', paddingLeft: 20 }}>
            <li>#ad disclosure in caption <i>and</i> on-screen during first 3 seconds.</li>
            <li>Tag @coolmate.vn. Use the campaign hashtag #SkinGlowDiary.</li>
            <li>No medical claims (e.g. "cures", "clears in X days").</li>
            <li>Natural-light grade preferred; we ship a LUT pack with the kit.</li>
          </ul>

          <h3 style={{ fontFamily: 'Space Grotesk', fontSize: 16 }}>4. Payment terms</h3>
          <p style={{ fontSize: 13.5, margin: '4px 0 18px' }}>
            Deliverable-tied. Each post pays within 7 business days of approval. Final wrap pays a 30% bonus
            ($540) on Jun 11 if reach targets are met.
          </p>

          <h3 style={{ fontFamily: 'Space Grotesk', fontSize: 16 }}>5. Usage &amp; exclusivity</h3>
          <p style={{ fontSize: 13.5, margin: '4px 0 0' }}>
            Coolmate may whitelist your posts for 30 days organically. No competing skincare brand collabs
            through Jul 11, 2026.
          </p>

          <div style={{ marginTop: 24, padding: 14, background: 'var(--bg-soft)', borderRadius: 8, fontSize: 12 }}>
            <b>Brand contact:</b> Trang Lê — Head of Brand, Coolmate · trang@coolmate.vn · WhatsApp +84 90 555 0142
          </div>
        </div>
      </div>
    </Modal>
  );
}

// ── 4. AI caption suggest panel ────────────────────────────────────
function AISuggestModal({ open, onClose, onPick }) {
  const [loading, setLoading] = React.useState(true);
  const [tone, setTone] = React.useState('honest');

  React.useEffect(() => {
    if (!open) return;
    setLoading(true);
    const id = setTimeout(() => setLoading(false), 900);
    return () => clearTimeout(id);
  }, [open, tone]);

  const SUGGESTIONS = {
    honest: [
      "Day 14 of Coolmate Vit-C. Real lighting, no filter. Here's what changed — and what didn't.\n\n#ad #SkinGlowDiary @coolmate.vn",
      "Tried to be skeptical. Was not skeptical for long ✨ Full ingredient nerdery in the comments. \n\n#ad #vitaminc #SkinGlowDiary @coolmate.vn",
      "If you've been on the fence about Vit-C, this is your sign. Honest 14-day review with @coolmate.vn.\n\n#ad #skincare",
    ],
    playful: [
      "POV: ur niacinamide finally hits and so does ur Vit-C ✨🍊\n\n#ad with @coolmate.vn · routine in comments #SkinGlowDiary",
      "girl who used to skip morning routine → girl who Has Opinions about acid order. blame @coolmate.vn 🧴\n\n#ad",
      "Vit-C drama in 3 acts: skeptical → cautiously hopeful → glow gang for life. Full routine ⬇️\n\n#ad @coolmate.vn",
    ],
    educational: [
      "Why L-ascorbic acid > the cheap stuff: pH stability, encapsulation, and why 10% is the sweet spot. A thread.\n\n#ad @coolmate.vn #SkinGlowDiary",
      "Niacinamide and Vit-C in the same routine? Yes, with one caveat. Here's the order I land on after 14 days.\n\n#ad @coolmate.vn",
      "If your Vit-C goes orange, that's oxidation — and it still works (for a bit). Storage, pH, layering. Quick breakdown ⬇️\n\n#ad @coolmate.vn",
    ],
  };

  return (
    <Modal open={open} onClose={onClose} width={620}
      title="AI caption suggestions"
      subtitle="Three options tuned to your past top posts · pick one or remix">
      <div className="row items-center gap-6 mb-4">
        <span className="cap-label" style={{ fontSize: 9 }}>Tone</span>
        {[
          ['honest', 'Honest'],
          ['playful', 'Playful'],
          ['educational', 'Educational'],
        ].map(([k, l]) => (
          <button key={k} onClick={() => setTone(k)} style={{
            padding: '5px 12px', borderRadius: 999, border: 0, cursor: 'pointer', fontFamily: 'inherit',
            background: tone === k ? 'var(--ink)' : 'var(--bg-soft)',
            color: tone === k ? 'white' : 'var(--ink-soft)',
            fontWeight: 700, fontSize: 12
          }}>{l}</button>
        ))}
        <span className="muted" style={{ fontSize: 11, marginLeft: 'auto' }}>
          {loading ? '✨ Generating…' : `3 options · ${tone}`}
        </span>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, minHeight: 280 }}>
        {loading ? (
          [0, 1, 2].map(i => (
            <div key={i} style={{ padding: 16, borderRadius: 12, background: 'var(--bg-soft)', height: 86 }}>
              <div style={{ height: 8, width: '60%', background: 'var(--line)', borderRadius: 4, marginBottom: 8, animation: 'pulse 1.2s infinite' }} />
              <div style={{ height: 8, width: '92%', background: 'var(--line)', borderRadius: 4, marginBottom: 8, animation: 'pulse 1.2s .15s infinite' }} />
              <div style={{ height: 8, width: '38%', background: 'var(--line)', borderRadius: 4, animation: 'pulse 1.2s .3s infinite' }} />
            </div>
          ))
        ) : SUGGESTIONS[tone].map((s, i) => (
          <div key={i} style={{
            padding: 14, borderRadius: 12, background: 'var(--bg-soft)',
            border: '2px solid transparent', transition: 'border-color .2s, background .2s',
            animation: `cardIn .35s ${i * 80}ms backwards cubic-bezier(.4,0,.2,1)`
          }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--cyan)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = 'transparent'; }}>
            <div style={{ fontSize: 12.5, lineHeight: 1.5, whiteSpace: 'pre-wrap', marginBottom: 10 }}>{s}</div>
            <div className="row items-center justify-between">
              <div className="row gap-6">
                <Pill variant="cyan">#ad ✓</Pill>
                <Pill variant="cyan">@coolmate.vn ✓</Pill>
                <Pill variant="mint">{s.length} chars</Pill>
              </div>
              <button onClick={() => { onPick(s); onClose(); }} className="btn btn-primary btn-sm">Use this {Icon.arrow}</button>
            </div>
          </div>
        ))}
      </div>
    </Modal>
  );
}

// ── 5. Time picker popover ─────────────────────────────────────────
function TimePickerModal({ open, onClose, onPick, initial = '7:00 PM' }) {
  const [date, setDate] = React.useState('May 22');
  const [hour, setHour] = React.useState(7);
  const [meridiem, setMeridiem] = React.useState('PM');

  const dates = ['May 22', 'May 23', 'May 24', 'May 25', 'May 26'];
  const hours = [10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  const peakHours = { 7: '+18%', 8: '+22%', 9: '+12%', 12: '+6%' };
  const isPeak = meridiem === 'PM' && peakHours[hour];

  return (
    <Modal open={open} onClose={onClose} width={520}
      title="Pick another time"
      subtitle="Posting window shapes your reach — peak hours are highlighted"
      footer={
        <div className="row gap-8">
          <button onClick={onClose} className="btn btn-ghost btn-sm">Cancel</button>
          <button onClick={() => { onPick(`${date} · ${hour}:00 ${meridiem}`); onClose(); }} className="btn btn-primary btn-sm">
            Set to {date} · {hour}:00 {meridiem}
          </button>
        </div>
      }>
      <div className="cap-label mb-2">Date</div>
      <div className="row gap-6 mb-4" style={{ flexWrap: 'wrap' }}>
        {dates.map(d => (
          <button key={d} onClick={() => setDate(d)} style={{
            padding: '8px 14px', borderRadius: 10, border: 0, cursor: 'pointer', fontFamily: 'inherit',
            background: date === d ? 'var(--ink)' : 'var(--bg-soft)',
            color: date === d ? 'white' : 'var(--ink)', fontWeight: 700, fontSize: 13
          }}>{d}</button>
        ))}
      </div>

      <div className="cap-label mb-2">Hour</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 6, marginBottom: 14 }}>
        {hours.map(h => {
          const sel = h === hour;
          const peak = meridiem === 'PM' && peakHours[h];
          return (
            <button key={h} onClick={() => setHour(h)} style={{
              padding: '10px 0', borderRadius: 10, border: 0, cursor: 'pointer', fontFamily: 'inherit', position: 'relative',
              background: sel ? 'var(--cyan)' : peak ? 'rgba(0,156,255,0.08)' : 'var(--bg-soft)',
              color: sel ? 'white' : 'var(--ink)', fontWeight: 700, fontSize: 13
            }}>
              {h}:00
              {peak && !sel && <span style={{ display: 'block', fontSize: 9, color: 'var(--cyan-dark)', fontWeight: 800 }}>{peak}</span>}
            </button>
          );
        })}
      </div>

      <div className="row gap-6 mb-4">
        {['AM', 'PM'].map(m => (
          <button key={m} onClick={() => setMeridiem(m)} style={{
            padding: '8px 16px', borderRadius: 999, border: 0, cursor: 'pointer', fontFamily: 'inherit',
            background: meridiem === m ? 'var(--ink)' : 'var(--bg-soft)',
            color: meridiem === m ? 'white' : 'var(--ink)', fontWeight: 700, fontSize: 13
          }}>{m}</button>
        ))}
      </div>

      <div className="row items-center gap-12" style={{ padding: 14, background: isPeak ? 'rgba(31,214,180,0.08)' : 'rgba(0,156,255,0.06)', borderRadius: 12, border: '1px solid ' + (isPeak ? 'rgba(31,214,180,0.3)' : 'rgba(0,156,255,0.2)') }}>
        <div style={{ fontSize: 24 }}>{isPeak ? '🔥' : '🕒'}</div>
        <div>
          <div className="bold">{date} · {hour}:00 {meridiem}</div>
          <div className="muted" style={{ fontSize: 11 }}>
            {isPeak ? `Peak engagement window · projected ${isPeak} reach vs avg` : 'Outside peak — fine, just not optimal'}
          </div>
        </div>
      </div>
    </Modal>
  );
}

// ── Host component + hook ──────────────────────────────────────────
const ActionsCtx = React.createContext(null);

function CampaignActionsHost({ children }) {
  const [msgOpen, setMsgOpen] = React.useState(false);
  const [msgPrefill, setMsgPrefill] = React.useState('');
  const [shipOpen, setShipOpen] = React.useState(false);
  const [pdfOpen, setPdfOpen] = React.useState(false);
  const [aiOpen, setAiOpen] = React.useState(false);
  const [aiCb, setAiCb] = React.useState(() => () => {});
  const [timeOpen, setTimeOpen] = React.useState(false);
  const [timeCb, setTimeCb] = React.useState(() => () => {});
  const [toast, setToast] = React.useState(null);

  const showToast = React.useCallback((message, kind = 'success', action) => {
    setToast({ message, kind, action });
  }, []);

  const api = React.useMemo(() => ({
    openMessage: (prefill = '') => { setMsgPrefill(prefill); setMsgOpen(true); },
    openShipment: () => setShipOpen(true),
    openBriefPdf: () => setPdfOpen(true),
    openAISuggest: (cb) => { setAiCb(() => cb); setAiOpen(true); },
    openTimePicker: (cb) => { setTimeCb(() => cb); setTimeOpen(true); },
    toast: showToast,
  }), [showToast]);

  return (
    <ActionsCtx.Provider value={api}>
      {children}
      <MessageTrangModal  open={msgOpen}  onClose={() => setMsgOpen(false)}  prefill={msgPrefill} />
      <ShipmentDrawer     open={shipOpen} onClose={() => setShipOpen(false)} />
      <BriefPdfModal      open={pdfOpen}  onClose={() => setPdfOpen(false)}
        onDownloaded={() => showToast('Brief PDF downloaded · Vitamin-C-Skin-Glow-v1.2.pdf', 'success')} />
      <AISuggestModal     open={aiOpen}   onClose={() => setAiOpen(false)}   onPick={(s) => aiCb(s)} />
      <TimePickerModal    open={timeOpen} onClose={() => setTimeOpen(false)} onPick={(t) => timeCb(t)} />
      <Toast open={!!toast} onClose={() => setToast(null)}
        kind={toast?.kind} message={toast?.message} action={toast?.action} />
    </ActionsCtx.Provider>
  );
}

function useCampaignActions() {
  return React.useContext(ActionsCtx) || {
    openMessage: () => {}, openShipment: () => {}, openBriefPdf: () => {},
    openAISuggest: () => {}, openTimePicker: () => {}, toast: () => {}
  };
}

Object.assign(window, { CampaignActionsHost, useCampaignActions });
