/* ============================================================
   MESSAGES — crew channels & broadcast
   Department channels with a live thread + composer. Messages you
   send are appended and persisted locally (backend-ready: swap the
   msgSave call for a socket emit). Seeded with realistic chatter.
   ============================================================ */

const MSG_KEY = 'silverlines.messages.' + (window.PROJ_ID || 'crimson') + '.v1';

const MSG_CHANNELS = [
  { id:'general',   name:'general',    icon:'Hash',  desc:'Whole unit' },
  { id:'camera',    name:'camera',     icon:'Hash',  desc:'Camera & DIT' },
  { id:'art',       name:'art-dept',   icon:'Hash',  desc:'Art & set dressing' },
  { id:'callsheets',name:'call-sheets',icon:'Megaphone', desc:'Broadcast · read-mostly' },
];

const PEEPS = {
  noor:  { name:'Noor Haddad',   role:'Producer',  color:'#22D48A' },
  dahlia:{ name:'Dahlia Mercer', role:'Director',  color:'#F57F45' },
  idris: { name:'Idris Vance',   role:'DP',        color:'#5FB0E8' },
  lucia: { name:'Lucia Romano',  role:'Designer',  color:'#9B8BE8' },
  marcus:{ name:'Marcus Hale',   role:'1st AD',    color:'#FF6FA5' },
};

const MSG_SEED = {
  general: [
    { id:'m1', who:'marcus', text:'Day 2 call sheet is out — gates open 05:30, breakfast on the truck.', ts: Date.now() - 1000 * 60 * 180 },
    { id:'m2', who:'dahlia', text:'Great work on the cockpit ignition. Tomorrow we chase the light early.', ts: Date.now() - 1000 * 60 * 120 },
    { id:'m3', who:'noor',   text:'Runway permit confirmed for the golden-hour window. Do not overrun.', ts: Date.now() - 1000 * 60 * 90 },
  ],
  camera: [
    { id:'c1', who:'idris', text:'Bringing the 32mm and 50mm for the hero. DIT cart by the north door.', ts: Date.now() - 1000 * 60 * 200 },
    { id:'c2', who:'noor',  text:'Copy. Backups running to the vault after each card.', ts: Date.now() - 1000 * 60 * 60 },
  ],
  art: [
    { id:'a1', who:'lucia', text:'Cockpit greeblies repainted in brand crimson. Photos in the location library.', ts: Date.now() - 1000 * 60 * 240 },
  ],
  callsheets: [
    { id:'k1', who:'marcus', text:'📢 DAY 2 — Call 05:30 · Runway 19 · Weather: clear, wind 8kt · Lunch 12:30.', ts: Date.now() - 1000 * 60 * 300 },
  ],
};

function msgLoad() {
  const s = window.SLStore.get(MSG_KEY); if (s && typeof s === 'object') return s;
  if (window.PROJ_BLANK) { const empty = {}; MSG_CHANNELS.forEach(c => empty[c.id] = []); return empty; }
  return MSG_SEED;
}
function myIdentity() {
  const st = window.SLStore.get('silverlines.settings.v1', {}); if (st.name) return { name: st.name, role: st.role || 'You', color:'#22D48A' };
  return PEEPS.noor;
}
const msgAgo = ts => {
  const m = Math.round((Date.now() - ts) / 60000);
  if (m < 1) return 'now';
  if (m < 60) return m + 'm';
  const h = Math.round(m / 60);
  return h < 24 ? h + 'h' : Math.round(h / 24) + 'd';
};

function MessagesModule({ mobile, readOnly = false }) {
  const [chans, setChansState] = useState(msgLoad);
  const setChans = next => setChansState(prev => {
    const v = typeof next === 'function' ? next(prev) : next;
    window.SLStore.set(MSG_KEY, v);
    return v;
  });
  const [active, setActive] = useState('general');
  const [draft, setDraft] = useState('');
  const SEEN_KEY = 'silverlines.msgseen.' + (window.PROJ_ID || 'crimson') + '.v1';
  const [seen, setSeen] = useState(() => window.SLStore.get(SEEN_KEY, {}));
  const me = myIdentity();
  const endRef = useRef(null);

  const list = chans[active] || [];
  useEffect(() => { if (endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight; }, [active, list.length]);
  /* mark the open channel read so the badge shows genuine unread, not the total */
  useEffect(() => { setSeen(s => { const n = { ...s, [active]: list.length }; window.SLStore.set(SEEN_KEY, n); return n; }); }, [active, list.length]);

  const send = () => {
    const t = draft.trim(); if (!t) return;
    setChans(c => ({ ...c, [active]: [...(c[active] || []), { id:'u' + Date.now(), who:'__me', me:{ ...me }, text:t, ts: Date.now() }] }));
    setDraft('');
  };

  const unread = id => Math.max(0, (chans[id] || []).length - (seen[id] || 0));

  return (
    <div className="fade-up">
      {!readOnly && <SectionTitle kicker="Crew & departments · Comms" icon="MessagesSquare" title="Messages" />}

      <Panel pad={false} className="overflow-hidden">
        <div className={cx('grid', mobile ? 'grid-cols-1' : 'grid-cols-[200px_1fr]')} style={{ minHeight: mobile ? undefined : 520 }}>
          {/* channel list */}
          <div className={cx('border-line', mobile ? 'border-b p-2' : 'border-r p-2.5')}>
            {!mobile && <div className="px-2 pb-1.5 pt-1 text-[10px] font-700 uppercase tracking-[0.16em] text-zinc-500">Channels</div>}
            <div className={cx(mobile ? 'flex gap-1.5 overflow-x-auto' : 'space-y-0.5')}>
              {MSG_CHANNELS.map(ch => (
                <button key={ch.id} onClick={() => setActive(ch.id)}
                  className={cx('flex shrink-0 items-center gap-2 rounded-lg px-2.5 py-2 text-left transition-colors',
                    active === ch.id ? 'bg-ink-700 text-head' : 'text-zinc-400 hover:bg-ink-800 hover:text-zinc-200', mobile ? '' : 'w-full')}>
                  <Icon name={ch.icon} size={14} className={active === ch.id ? 'text-electric-soft' : 'text-zinc-600'} />
                  <span className="min-w-0 flex-1">
                    <span className="block truncate text-[12.5px] font-600">{ch.name}</span>
                    {!mobile && <span className="block truncate text-[10.5px] text-zinc-500">{ch.desc}</span>}
                  </span>
                  {unread(ch.id) > 0 && <span className="shrink-0 rounded-full bg-electric/15 px-1.5 py-0.5 font-mono text-[9.5px] font-700 text-electric-soft">{unread(ch.id)}</span>}
                </button>
              ))}
            </div>
          </div>

          {/* thread */}
          <div className="flex flex-col" style={{ height: mobile ? 460 : 520 }}>
            <div ref={endRef} className="flex-1 space-y-3 overflow-y-auto p-4">
              {list.length === 0 && <div className="py-10 text-center text-[12px] text-zinc-500">No messages in #{(MSG_CHANNELS.find(c => c.id === active) || {}).name} yet.</div>}
              {list.map(m => {
                const p = m.who === '__me' ? (m.me || me) : (PEEPS[m.who] || { name:'Crew', role:'', color:'#888' });
                const mine = m.who === '__me';
                return (
                  <div key={m.id} className={cx('flex gap-2.5', mine ? 'flex-row-reverse' : '')}>
                    <Avatar name={p.name} color={p.color} size={32} />
                    <div className={cx('min-w-0 max-w-[78%]', mine ? 'items-end text-right' : '')}>
                      <div className={cx('flex items-center gap-2 text-[11px]', mine ? 'flex-row-reverse' : '')}>
                        <span className="font-700 text-zinc-200">{mine ? 'You' : p.name}</span>
                        {p.role && <span className="text-zinc-600">{p.role}</span>}
                        <span className="text-zinc-600">{msgAgo(m.ts)}</span>
                      </div>
                      <div className={cx('mt-1 inline-block rounded-2xl px-3 py-2 text-[12.5px] leading-relaxed', mine ? 'bg-electric/15 text-zinc-100' : 'bg-ink-800 text-zinc-200')}>{m.text}</div>
                    </div>
                  </div>
                );
              })}
            </div>
            {/* composer */}
            {!readOnly && (
              <div className="flex items-center gap-2 border-t border-line p-3">
                <Avatar name={me.name} color={me.color} size={30} />
                <input value={draft} onChange={e => setDraft(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') send(); }}
                  placeholder={`Message #${(MSG_CHANNELS.find(c => c.id === active) || {}).name}…`}
                  className="min-w-0 flex-1 rounded-xl border border-line bg-ink-900 px-3.5 py-2.5 text-[12.5px] text-zinc-200 outline-none focus:border-electric/60" />
                <button onClick={send} disabled={!draft.trim()}
                  className={cx('flex h-10 w-10 shrink-0 items-center justify-center rounded-xl transition-colors', draft.trim() ? 'bg-cta text-cta-ink hover:bg-cta-hover' : 'cursor-not-allowed bg-ink-700 text-zinc-500')}>
                  <Icon name="Send" size={16} />
                </button>
              </div>
            )}
          </div>
        </div>
      </Panel>
    </div>
  );
}

window.MessagesModule = MessagesModule;
window.MSG_CHANNELS = MSG_CHANNELS;
window.msgLoad = msgLoad;
