/* Mereka v2 — Broadcast feature (list + popups + template builder) — Figma rebuild */

/* ===================== Data ===================== */
const BC_TEMPLATES = [
  { id: 't1', name: 'Onboarding template', channel: 'Whatsapp', updated: '52 minutes ago', category: 'Onboarding', language: 'English', status: 'Approved' },
  { id: 't2', name: 'Programme completion', channel: 'Email', updated: '5d ago', category: 'Marketing', language: 'English', status: 'Approved' },
  { id: 't3', name: 'Event Reminder', channel: 'Whatsapp', updated: '3/10/2024', category: 'Reminder', language: 'English', status: 'Pending' },
  { id: 't4', name: 'Event Reminder', channel: 'Whatsapp', updated: '3/10/2024', category: 'Reminder', language: 'Malay', status: 'Draft' },
  { id: 't5', name: 'Meeting Schedule', channel: 'Email', updated: '3/15/2024', category: 'Marketing', language: 'English', status: 'Pending' },
  { id: 't6', name: 'Project Kickoff', channel: 'Email', updated: '4/01/2024', category: 'Marketing', language: 'English', status: 'Approved' },
  { id: 't7', name: 'Team Outing', channel: 'Whatsapp', updated: '4/10/2024', category: 'Onboarding', language: 'English', status: 'Pending' },
  { id: 't8', name: 'Quarterly Review', channel: 'Whatsapp', updated: '4/25/2024', category: 'Programme', language: 'English', status: 'Approved' },
  { id: 't9', name: 'Training Session', channel: 'Email', updated: '5/05/2024', category: 'Programme', language: 'Malay', status: 'Draft' },
  { id: 't10', name: 'Feedback Session', channel: 'Email', updated: '5/20/2024', category: 'Experience', language: 'Malay', status: 'Draft' },
];

const BC_MESSAGES = [
  { id: 'm1', name: 'Onboarding template', channel: 'Whatsapp', status: 'Scheduled', sent: '3/10/2024, 12:00', category: 'Onboarding' },
  { id: 'm2', name: 'Programme completion', channel: 'Email', status: 'Sent', sent: '3/10/2024, 13:00', category: 'Marketing' },
  { id: 'm3', name: 'Event Reminder', channel: 'Whatsapp', status: 'Sent', sent: '3/10/2024, 21:00', category: 'Reminder' },
  { id: 'm4', name: 'Event Reminder', channel: 'Whatsapp', status: 'Sent', sent: '3/10/2024, 17:30', category: 'Reminder' },
];
const BC_TEMPLATES_BY_HUB = [
  BC_TEMPLATES,
  [
    { id: 'mt1', name: 'AI Cohort Welcome', channel: 'Whatsapp', updated: '1 hour ago', category: 'Onboarding', language: 'English', status: 'Approved' },
    { id: 'mt2', name: 'Weekly Build Digest', channel: 'Email', updated: '2d ago', category: 'Marketing', language: 'English', status: 'Approved' },
    { id: 'mt3', name: 'Office Hours Reminder', channel: 'Whatsapp', updated: '3d ago', category: 'Reminder', language: 'English', status: 'Pending' },
    { id: 'mt4', name: 'Demo Day Invite', channel: 'Email', updated: '4d ago', category: 'Marketing', language: 'English', status: 'Approved' },
    { id: 'mt5', name: 'Beta Feedback Request', channel: 'Email', updated: '1w ago', category: 'Experience', language: 'English', status: 'Draft' },
  ],
  [
    { id: 'st1', name: 'Client Onboarding', channel: 'Email', updated: '2 hours ago', category: 'Onboarding', language: 'English', status: 'Approved' },
    { id: 'st2', name: 'Project Milestone Update', channel: 'Email', updated: '1d ago', category: 'Programme', language: 'English', status: 'Approved' },
    { id: 'st3', name: 'Invoice Reminder', channel: 'Whatsapp', updated: '4d ago', category: 'Reminder', language: 'English', status: 'Pending' },
    { id: 'st4', name: 'Studio Newsletter', channel: 'Email', updated: '1w ago', category: 'Marketing', language: 'English', status: 'Draft' },
  ],
];
const BC_MESSAGES_BY_HUB = [
  BC_MESSAGES,
  [
    { id: 'mm1', name: 'AI Cohort Welcome', channel: 'Whatsapp', status: 'Sent', sent: '5/02/2026, 09:00', category: 'Onboarding' },
    { id: 'mm2', name: 'Office Hours Reminder', channel: 'Whatsapp', status: 'Scheduled', sent: '5/06/2026, 16:00', category: 'Reminder' },
    { id: 'mm3', name: 'Demo Day Invite', channel: 'Email', status: 'Sent', sent: '4/28/2026, 10:00', category: 'Marketing' },
    { id: 'mm4', name: 'Weekly Build Digest', channel: 'Email', status: 'Sent', sent: '4/26/2026, 08:30', category: 'Marketing' },
  ],
  [
    { id: 'sm1', name: 'Client Onboarding', channel: 'Email', status: 'Sent', sent: '5/03/2026, 11:00', category: 'Onboarding' },
    { id: 'sm2', name: 'Project Milestone Update', channel: 'Email', status: 'Sent', sent: '5/01/2026, 14:30', category: 'Programme' },
    { id: 'sm3', name: 'Invoice Reminder', channel: 'Whatsapp', status: 'Scheduled', sent: '5/08/2026, 09:30', category: 'Reminder' },
  ],
];

const BC_STATUS_TONE = {
  Approved: 'text-green-600',
  Pending: 'text-amber-500',
  Draft: 'text-neutral-500',
  Scheduled: 'text-blue-600',
  Sent: 'text-green-600',
};

/* ===================== Shared bits ===================== */
function BcFilterChip({ label, onRemove }) {
  return (
    <span className="inline-flex items-center gap-2 h-9 px-3.5 border border-neutral-200 rounded-full text-sm text-neutral-700 bg-white">
      {label}
      <button onClick={onRemove} className="text-neutral-400 hover:text-neutral-700"><Icon name="close" size={13} /></button>
    </span>
  );
}

function BcFilterPopover({ options, selected, onToggle, onClear, onApply, applyLabel = 'Apply filter' }) {
  return (
    <div onClick={e => e.stopPropagation()}
      className="absolute right-0 top-12 w-[300px] bg-white rounded-2xl border border-neutral-100 p-5 z-30"
      style={{ boxShadow: '0 16px 44px rgba(0,0,0,0.14)' }}>
      <div className="space-y-3.5">
        {options.map(o => {
          const on = selected.includes(o);
          return (
            <label key={o} className="flex items-center gap-3 cursor-pointer">
              <span className={`w-6 h-6 rounded-md flex items-center justify-center flex-shrink-0 transition-colors ${on ? 'bg-neutral-900 text-white' : 'border-2 border-neutral-300'}`}>
                {on && <Icon name="check" size={14} strokeWidth={3} />}
              </span>
              <span className="text-[15px] text-neutral-800" onClick={e => { e.preventDefault(); onToggle(o); }}>{o}</span>
            </label>
          );
        })}
      </div>
      <div className="flex items-center justify-end gap-3 mt-5">
        <button onClick={onClear} className="text-[15px] text-neutral-600 hover:text-neutral-900">Clear filter</button>
        <button onClick={onApply} className="h-10 px-5 rounded-full bg-neutral-900 text-white text-sm font-semibold hover:bg-neutral-800">{applyLabel}</button>
      </div>
    </div>
  );
}

function BcTemplateActionMenu({ onClose, onUse, onDuplicate, onView, onDelete, approved }) {
  const [tip, setTip] = useState(false);
  useEffect(() => {
    setTimeout(() => document.addEventListener('click', onClose, { once: true }), 0);
    return () => document.removeEventListener('click', onClose);
  }, []);
  return (
    <div onClick={e => e.stopPropagation()} className="absolute right-8 top-10 w-56 bg-white rounded-2xl border border-neutral-100 py-2 z-30"
      style={{ boxShadow: '0 16px 44px rgba(0,0,0,0.16)' }}>
      <button onClick={onUse} className="w-full flex items-center gap-3 px-5 py-2.5 text-[15px] hover:bg-neutral-50 text-left"><Icon name="mail" size={16} className="text-neutral-500" /> Use template</button>
      <div className="relative" onMouseEnter={() => approved && setTip(true)} onMouseLeave={() => setTip(false)}>
        <button disabled={approved} className={`w-full flex items-center gap-3 px-5 py-2.5 text-[15px] text-left ${approved ? 'text-neutral-300 cursor-not-allowed' : 'hover:bg-neutral-50'}`}>
          <Icon name="edit" size={16} className={approved ? 'text-neutral-300' : 'text-neutral-500'} /> Edit template
        </button>
        {tip && (
          <div className="absolute left-full top-0 ml-2 w-64 bg-white rounded-xl border border-neutral-100 p-4 text-[13px] text-neutral-700 leading-relaxed z-40" style={{ boxShadow: '0 12px 32px rgba(0,0,0,0.16)' }}>
            Note:<br />Approved templates can't be edited.<br />Workaround: Duplicate template, edit then submit for approval again.
          </div>
        )}
      </div>
      <button onClick={onDuplicate} className="w-full flex items-center gap-3 px-5 py-2.5 text-[15px] hover:bg-neutral-50 text-left"><Icon name="copy" size={16} className="text-neutral-500" /> Duplicate</button>
      <button onClick={onView} className="w-full flex items-center gap-3 px-5 py-2.5 text-[15px] hover:bg-neutral-50 text-left"><Icon name="eye" size={16} className="text-neutral-500" /> View details</button>
      <div className="border-t border-neutral-100 my-1.5" />
      <button onClick={onDelete} className="w-full flex items-center gap-3 px-5 py-2.5 text-[15px] text-red-600 hover:bg-red-50 text-left"><Icon name="trash" size={16} /> Delete</button>
    </div>
  );
}

/* ===================== Broadcast main page ===================== */
function BroadcastPage() {
  const [tab, setTab] = useState('templates');
  const [chips, setChips] = useState(['Whatsapp', 'Email', 'Onboarding', 'Reminder']);
  const [search, setSearch] = useState('');
  const [menuOpen, setMenuOpen] = useState(null);
  const [filterOpen, setFilterOpen] = useState(false);
  const [filterSel, setFilterSel] = useState(['Whatsapp', 'Email', 'Onboarding', 'Reminder']);

  const hub = useHub();
  const HUB_TEMPLATES = BC_TEMPLATES_BY_HUB[hubIdx(hub)] || BC_TEMPLATES;
  const HUB_MESSAGES = BC_MESSAGES_BY_HUB[hubIdx(hub)] || BC_MESSAGES;
  const templates = HUB_TEMPLATES.filter(t => search === '' || t.name.toLowerCase().includes(search.toLowerCase()));
  const messages = HUB_MESSAGES.filter(m => search === '' || m.name.toLowerCase().includes(search.toLowerCase()));

  return (
    <DashShell active="/app/dashboard/communication-logs">
      <div className="flex items-start justify-between mb-5 flex-wrap gap-3">
        <div>
          <h1 className="text-3xl font-bold">Broadcast</h1>
          <p className="text-[15px] text-neutral-500 mt-1">Send announcements, reminders, and updates to selected learners across WhatsApp and emails.</p>
        </div>
        <Link to="/app/broadcast/settings">
          <button className="inline-flex items-center gap-2 h-10 px-4 border border-neutral-300 rounded-lg text-sm font-medium bg-white hover:bg-neutral-50">
            <Icon name="settings" size={15} /> Settings
          </button>
        </Link>
      </div>

      <div className="flex items-center justify-between gap-3 mb-5 flex-wrap">
        <div className="flex items-center gap-2 bg-neutral-100 p-1 rounded-full">
          <button onClick={() => setTab('templates')} className={`h-9 px-5 rounded-full text-sm font-semibold transition-colors ${tab === 'templates' ? 'bg-neutral-900 text-white' : 'text-neutral-700'}`}>Templates</button>
          <button onClick={() => setTab('history')} className={`h-9 px-5 rounded-full text-sm font-semibold transition-colors ${tab === 'history' ? 'bg-neutral-900 text-white' : 'text-neutral-700'}`}>Message history</button>
        </div>
        {tab === 'templates' ? (
          <Link to="/app/broadcast/template/new">
            <button className="inline-flex items-center gap-2 h-11 px-5 bg-neutral-900 text-white rounded-full text-sm font-semibold hover:bg-neutral-800"><Icon name="plus" size={16} /> Create new template</button>
          </Link>
        ) : (
          <Link to="/app/broadcast/message/new">
            <button className="inline-flex items-center gap-2 h-11 px-5 bg-neutral-900 text-white rounded-full text-sm font-semibold hover:bg-neutral-800"><Icon name="plus" size={16} /> New message</button>
          </Link>
        )}
      </div>

      <div className="bg-white border border-neutral-200 rounded-2xl">
        {/* toolbar */}
        <div className="flex items-center justify-between gap-3 p-5 flex-wrap">
          <div className="flex items-center gap-2.5 flex-wrap">
            <h2 className="text-lg font-bold mr-1">{tab === 'templates' ? 'Templates' : 'Message history'}</h2>
            {tab === 'templates' && chips.map(c => <BcFilterChip key={c} label={c} onRemove={() => setChips(chips.filter(x => x !== c))} />)}
          </div>
          <div className="flex items-center gap-2">
            <div className="relative w-[240px]">
              <Icon name="search" size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400" />
              <input value={search} onChange={e => setSearch(e.target.value)}
                placeholder={tab === 'templates' ? 'Search templates...' : 'Search messages...'}
                className="w-full h-10 pl-11 pr-4 text-sm border border-neutral-200 rounded-full bg-white focus:outline-none focus:border-neutral-400" />
            </div>
            <div className="relative">
              <button onClick={e => { e.stopPropagation(); setFilterOpen(o => !o); }} className="w-10 h-10 rounded-lg border border-neutral-200 flex items-center justify-center text-neutral-600 hover:bg-neutral-50"><Icon name="filter" size={16} /></button>
              {filterOpen && (
                <BcFilterPopover
                  options={['All', 'Whatsapp', 'Email', 'Onboarding', 'Promotion', 'Reminder']}
                  selected={filterSel}
                  onToggle={(o) => setFilterSel(s => s.includes(o) ? s.filter(x => x !== o) : [...s, o])}
                  onClear={() => setFilterSel([])}
                  onApply={() => { setChips(filterSel.filter(x => x !== 'All')); setFilterOpen(false); }}
                />
              )}
            </div>
          </div>
        </div>

        {tab === 'templates' ? (
          <BcTemplatesTable templates={templates} menuOpen={menuOpen} setMenuOpen={setMenuOpen} />
        ) : (
          <BcMessagesTable messages={messages} menuOpen={menuOpen} setMenuOpen={setMenuOpen} />
        )}
      </div>

      <div className="flex items-center justify-between mt-4">
        <span className="text-sm text-neutral-500">{tab === 'templates' ? 'Showing 1-10 of 40' : 'Showing 1-4 of 4'}</span>
        <Pagination />
      </div>
    </DashShell>
  );
}

function BcTemplatesTable({ templates, menuOpen, setMenuOpen }) {
  return (
    <div className="overflow-x-auto border-t border-neutral-100">
      <table className="w-full text-sm min-w-[920px]">
        <thead>
          <tr className="text-neutral-500 border-b border-neutral-100">
            <th className="text-left px-5 py-3 font-medium w-10"><input type="checkbox" className="accent-neutral-900" /></th>
            <th className="text-left px-2 py-3 font-medium">Template Name</th>
            <th className="text-left px-2 py-3 font-medium">Channel</th>
            <th className="text-left px-2 py-3 font-medium">Last Updated</th>
            <th className="text-left px-2 py-3 font-medium">Category</th>
            <th className="text-left px-2 py-3 font-medium">Language</th>
            <th className="text-left px-2 py-3 font-medium">Status</th>
            <th className="text-left px-2 py-3 font-medium">Action</th>
          </tr>
        </thead>
        <tbody>
          {templates.map(t => (
            <tr key={t.id} className="border-b border-neutral-100 last:border-0 hover:bg-neutral-50">
              <td className="px-5 py-4"><input type="checkbox" className="accent-neutral-900" /></td>
              <td className="px-2 py-4 font-medium text-neutral-800">{t.name}</td>
              <td className="px-2 py-4 text-neutral-600">{t.channel}</td>
              <td className="px-2 py-4 text-neutral-600">{t.updated}</td>
              <td className="px-2 py-4 text-neutral-600">{t.category}</td>
              <td className="px-2 py-4 text-neutral-600">{t.language}</td>
              <td className={`px-2 py-4 font-medium ${BC_STATUS_TONE[t.status]}`}>{t.status}</td>
              <td className="px-2 py-4 relative">
                <div className="flex items-center gap-1.5">
                  <Link to="/app/broadcast/message/new">
                    <button className="h-9 px-4 border border-neutral-300 rounded-full text-sm font-medium bg-white hover:bg-neutral-50 whitespace-nowrap">Use template</button>
                  </Link>
                  <button onClick={e => { e.stopPropagation(); setMenuOpen(menuOpen === t.id ? null : t.id); }} className="text-neutral-500 hover:text-neutral-900 p-1"><Icon name="more" size={16} /></button>
                </div>
                {menuOpen === t.id && (
                  <BcTemplateActionMenu approved={t.status === 'Approved'} onClose={() => setMenuOpen(null)}
                    onUse={() => { setMenuOpen(null); navigate('/app/broadcast/message/new'); }}
                    onDuplicate={() => setMenuOpen(null)}
                    onView={() => { setMenuOpen(null); navigate('/app/broadcast/template/new'); }}
                    onDelete={() => setMenuOpen(null)} />
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function BcMessagesTable({ messages, menuOpen, setMenuOpen }) {
  return (
    <div className="overflow-x-auto border-t border-neutral-100">
      <table className="w-full text-sm min-w-[820px]">
        <thead>
          <tr className="text-neutral-500 border-b border-neutral-100">
            <th className="text-left px-5 py-3 font-medium w-10"><input type="checkbox" className="accent-neutral-900" /></th>
            <th className="text-left px-2 py-3 font-medium">Message Name</th>
            <th className="text-left px-2 py-3 font-medium">Channel</th>
            <th className="text-left px-2 py-3 font-medium">Status</th>
            <th className="text-left px-2 py-3 font-medium">Sent at</th>
            <th className="text-left px-2 py-3 font-medium">Category</th>
            <th className="text-left px-2 py-3 font-medium">Action</th>
          </tr>
        </thead>
        <tbody>
          {messages.map(m => (
            <tr key={m.id} className="border-b border-neutral-100 last:border-0 hover:bg-neutral-50">
              <td className="px-5 py-4"><input type="checkbox" className="accent-neutral-900" /></td>
              <td className="px-2 py-4 font-medium text-neutral-800">{m.name}</td>
              <td className="px-2 py-4 text-neutral-600">{m.channel}</td>
              <td className={`px-2 py-4 font-medium ${BC_STATUS_TONE[m.status]}`}>{m.status}</td>
              <td className="px-2 py-4 text-neutral-600">{m.sent}</td>
              <td className="px-2 py-4 text-neutral-600">{m.category}</td>
              <td className="px-2 py-4 relative">
                <div className="flex items-center gap-1.5">
                  <button className="h-9 px-5 border border-neutral-300 rounded-full text-sm font-medium bg-white hover:bg-neutral-50">View</button>
                  <button onClick={e => { e.stopPropagation(); setMenuOpen(menuOpen === m.id ? null : m.id); }} className="text-neutral-500 hover:text-neutral-900 p-1"><Icon name="more" size={16} /></button>
                </div>
                {menuOpen === m.id && (
                  <BcTemplateActionMenu approved={false} onClose={() => setMenuOpen(null)}
                    onUse={() => setMenuOpen(null)} onDuplicate={() => setMenuOpen(null)}
                    onView={() => setMenuOpen(null)} onDelete={() => setMenuOpen(null)} />
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, { BroadcastPage });
