/* Mereka v2 — Broadcast "Create message" wizard (Audience/Content/Preview/Schedule) — Figma rebuild */

const BC_WIZARD_STEPS = ['Audience', 'Content', 'Preview', 'Schedule'];

const BC_RECIPIENTS = [
  'young.zheng@uxagents.com', 'nicholashon@uxagents.com', 'faiz@mereka.my', 'florencejones@gmail.com', 'natalie123a@gmail.com', 'james.smith@outlook.com',
  'samantha.jones@yahoo.com', 'michael.brown@gmail.com', 'emily.davis@hotmail.com', 'chris.wilson@icloud.com', 'olivia.johnson@fakemail.com', 'daniel.miller@live.com',
];
const BC_APPROVED_TEMPLATES = [
  { id: 'a1', name: 'Onboarding message_1', channel: 'Whatsapp', updated: '52 minutes ago', category: 'Onboarding', language: 'English' },
  { id: 'a2', name: 'Marketing_1', channel: 'Whatsapp', updated: '52 minutes ago', category: 'Onboarding', language: 'English' },
  { id: 'a3', name: 'May 2026 Promo', channel: 'Whatsapp', updated: '52 minutes ago', category: 'Onboarding', language: 'English' },
];

/* ===== Multi-select dropdown (programmes / cohort) ===== */
function BcMultiSelect({ placeholder, options, onAdd }) {
  const [open, setOpen] = useState(false);
  const [sel, setSel] = useState([options[1], options[2], options[3]].filter(Boolean));
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('click', h);
    return () => document.removeEventListener('click', h);
  }, [open]);
  const toggle = (o) => setSel(s => s.includes(o) ? s.filter(x => x !== o) : [...s, o]);
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen(o => !o)} className="w-full h-14 px-5 border border-neutral-200 rounded-xl flex items-center justify-between text-left hover:border-neutral-300">
        <span className="text-neutral-400 text-[16px]">{placeholder}</span>
        <Icon name="chevronDown" size={18} className={`text-neutral-500 transition-transform ${open ? 'rotate-180' : ''}`} />
      </button>
      {open && (
        <div className="absolute left-0 top-[calc(100%+6px)] w-full min-w-[360px] bg-white rounded-2xl border border-neutral-100 z-30" style={{ boxShadow: '0 16px 44px rgba(0,0,0,0.14)' }}>
          <div className="flex items-center gap-2.5 px-4 h-12 border-b border-neutral-100">
            <Icon name="search" size={18} className="text-neutral-400" />
            <input placeholder="Search programmes..." className="flex-1 text-[15px] focus:outline-none bg-transparent" />
          </div>
          <div className="py-2 max-h-[260px] overflow-y-auto">
            {options.map(o => {
              const on = sel.includes(o);
              return (
                <button key={o} onClick={() => toggle(o)} className="w-full flex items-center gap-3 px-4 py-2.5 hover:bg-neutral-50 text-left">
                  <span className={`w-6 h-6 rounded-md flex items-center justify-center flex-shrink-0 ${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">{o}</span>
                </button>
              );
            })}
          </div>
          <div className="flex items-center justify-end gap-3 px-4 py-3 border-t border-neutral-100">
            <button onClick={() => setSel([])} className="text-[15px] text-neutral-600 hover:text-neutral-900">Clear filter</button>
            <button onClick={() => { onAdd && onAdd(sel); setOpen(false); }} className="h-10 px-5 rounded-full bg-neutral-900 text-white text-sm font-semibold hover:bg-neutral-800">Add as recipients</button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ===== Service category radio dropdown ===== */
function BcRadioSelect({ placeholder, options, value, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('click', h);
    return () => document.removeEventListener('click', h);
  }, [open]);
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen(o => !o)} className="w-full h-14 px-5 border border-neutral-200 rounded-xl flex items-center justify-between text-left hover:border-neutral-300">
        <span className={value ? 'text-neutral-900 text-[16px]' : 'text-neutral-400 text-[16px]'}>{value || placeholder}</span>
        <Icon name="chevronDown" size={18} className={`text-neutral-500 transition-transform ${open ? 'rotate-180' : ''}`} />
      </button>
      {open && (
        <div className="absolute left-0 top-[calc(100%+6px)] w-full bg-white rounded-2xl border border-neutral-100 p-2 z-30" style={{ boxShadow: '0 16px 44px rgba(0,0,0,0.14)' }}>
          {options.map(o => (
            <button key={o} onClick={() => { onChange(o); setOpen(false); }} className="w-full flex items-center gap-3 px-3 py-3 rounded-xl hover:bg-neutral-50 text-left">
              <span className={`w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0 ${value === o ? 'border-2 border-neutral-900' : 'border-2 border-neutral-300'}`}>{value === o && <span className="w-3 h-3 rounded-full bg-neutral-900" />}</span>
              <span className="text-[15px] text-neutral-800">{o}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function BcEmailChip({ email, onRemove }) {
  return (
    <span className="inline-flex items-center gap-2 h-10 px-4 border border-neutral-200 rounded-full text-[14px] text-neutral-700 bg-white">
      {email}
      <button onClick={onRemove} className="text-neutral-400 hover:text-neutral-700"><Icon name="close" size={13} /></button>
    </span>
  );
}

/* ===== Wizard shell ===== */
function CreateMessageWizardPage() {
  const [step, setStep] = useState('Audience');
  const idx = BC_WIZARD_STEPS.indexOf(step);
  const next = () => { if (idx < 3) setStep(BC_WIZARD_STEPS[idx + 1]); };

  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <div className="max-w-[min(2100px,92vw)] mx-auto grid grid-cols-1 lg:grid-cols-[260px_1fr] gap-6 px-5 lg:px-10 py-8">
        {/* Wizard nav */}
        <aside>
          <Link to="/app/dashboard/communication-logs" className="inline-flex w-10 h-10 items-center justify-center rounded-full text-neutral-500 hover:bg-neutral-100 mb-4"><Icon name="chevronLeft" size={20} /></Link>
          <h2 className="text-2xl font-bold mb-7">Create message</h2>
          <nav className="space-y-2">
            {BC_WIZARD_STEPS.map(s => (
              <button key={s} onClick={() => setStep(s)}
                className={`block px-5 py-2.5 rounded-full text-[16px] transition-colors ${step === s ? 'bg-neutral-900 text-white font-semibold' : 'text-neutral-800 hover:bg-neutral-100'}`}>
                {s}
              </button>
            ))}
          </nav>
        </aside>

        {/* Step content */}
        <div className="space-y-5">
          <div className="bg-white border border-neutral-200 rounded-2xl p-8 min-h-[560px]">
            {step === 'Audience' && <BcAudienceStep />}
            {step === 'Content' && <BcContentStep />}
            {step === 'Preview' && <BcPreviewStep />}
            {step === 'Schedule' && <BcScheduleStep />}
          </div>
          <div className="bg-white border border-neutral-200 rounded-2xl px-8 py-5 flex items-center justify-end">
            {step === 'Schedule' ? (
              <Link to="/app/dashboard/communication-logs"><button className="h-12 px-8 rounded-full bg-neutral-900 text-white text-[15px] font-semibold hover:bg-neutral-800">Schedule message</button></Link>
            ) : (
              <button onClick={next} className="h-12 px-8 rounded-full bg-neutral-900 text-white text-[15px] font-semibold hover:bg-neutral-800">Save &amp; Continue</button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ===== Audience ===== */
function BcAudienceStep() {
  const [serviceCat, setServiceCat] = useState('');
  const [recipients, setRecipients] = useState(BC_RECIPIENTS.concat(BC_RECIPIENTS.slice(0, 8)));
  const cohorts = [
    { name: 'AI ACCELERATOR (AI4U)', meta: 'Programme', cohort: 'Cohort APR 2026', tone: 'text-neutral-500' },
    { name: 'AI ACCELERATOR (AI4U)', meta: 'Programme', cohort: 'Cohort APR 2026', tone: 'text-neutral-500' },
    { name: 'GENERATIVE AI WOR...', meta: 'Experience', cohort: 'Cohort APR 2026', tone: 'text-amber-500' },
  ];
  return (
    <>
      <h1 className="text-3xl font-bold">Audience</h1>
      <p className="text-[15px] text-neutral-500 mt-1 mb-7">Choose which group of users will receive this broadcast.</p>

      <div className="grid md:grid-cols-2 gap-6 mb-7">
        <div>
          <label className="block text-[15px] font-bold mb-2">Service category</label>
          <BcRadioSelect placeholder="Select programme or experience" value={serviceCat} onChange={setServiceCat} options={['Programme', 'Experiences', 'Standalone']} />
        </div>
        <div>
          <label className="block text-[15px] font-bold mb-2">Cohort</label>
          <BcMultiSelect placeholder="Select cohort" options={['All programmes', 'AI4U', 'AI Fluency by Microsoft', 'AI First Designer School', 'Explore Generative AI', 'Get Started with Microsoft Copilot']} />
        </div>
      </div>

      <h3 className="text-[17px] font-bold mb-3">Cohorts ({cohorts.length})</h3>
      <div className="flex items-center gap-3 mb-7 flex-wrap">
        {cohorts.map((c, i) => (
          <div key={i} className="inline-flex items-center gap-3 px-4 py-2.5 border border-neutral-200 rounded-xl">
            <div>
              <p className="text-[13px] font-bold text-neutral-800 leading-tight">{c.name}</p>
              <p className="text-[12px] leading-tight"><span className={c.tone}>{c.meta}</span> <span className="text-neutral-400">• {c.cohort}</span></p>
            </div>
            <button className="text-neutral-400 hover:text-neutral-700"><Icon name="close" size={14} /></button>
          </div>
        ))}
      </div>

      <h3 className="text-[17px] font-bold mb-3">Recipient list ({recipients.length})</h3>
      <div className="relative mb-4">
        <Icon name="search" size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400" />
        <input placeholder="Search email" className="w-full h-12 pl-12 pr-4 text-[15px] border border-neutral-200 rounded-xl focus:outline-none focus:border-neutral-400" />
      </div>
      <div className="flex flex-wrap gap-2.5">
        {recipients.map((e, i) => <BcEmailChip key={i} email={e} onRemove={() => setRecipients(recipients.filter((_, j) => j !== i))} />)}
      </div>
    </>
  );
}

/* ===== Content ===== */
function BcContentStep() {
  const [channel, setChannel] = useState('Email');
  const [tpl, setTpl] = useState('a1');
  return (
    <>
      <h1 className="text-3xl font-bold">Content</h1>
      <p className="text-[15px] text-neutral-500 mt-1 mb-7">Choose which group of users will receive this broadcast.</p>

      <label className="block text-[15px] font-bold mb-3">Select message channel</label>
      <div className="space-y-3 mb-2">
        <BcSelectRow label="Email" checked={channel === 'Email'} onClick={() => setChannel('Email')} />
        <BcSelectRow label="Whatsapp" checked={channel === 'Whatsapp'} onClick={() => setChannel('Whatsapp')} />
      </div>
      <p className="text-[13px] text-neutral-500 mb-7">Messages sent via WhatsApp will only be delivered to recipients with an active WhatsApp account.</p>

      <h3 className="text-2xl font-bold mb-1">Select approved template</h3>
      <p className="text-[15px] text-neutral-500 mb-4">Choose which template to use for your message.</p>
      <div className="border border-neutral-200 rounded-2xl overflow-hidden mb-8">
        <div className="flex items-center gap-2.5 px-5 py-4 flex-wrap">
          <h4 className="font-bold mr-1">Templates</h4>
          {['Whatsapp', 'Onboarding', 'Reminder'].map(c => (
            <span key={c} className="inline-flex items-center gap-2 h-8 px-3 border border-neutral-200 rounded-full text-[13px] text-neutral-700">{c} <Icon name="close" size={12} className="text-neutral-400" /></span>
          ))}
          <div className="ml-auto relative w-[220px]">
            <Icon name="search" size={15} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-neutral-400" />
            <input placeholder="Search templates..." className="w-full h-9 pl-10 pr-3 text-sm border border-neutral-200 rounded-full focus:outline-none" />
          </div>
        </div>
        <table className="w-full text-sm">
          <thead>
            <tr className="text-neutral-500 border-y border-neutral-100">
              <th className="text-left px-5 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="px-5 py-3 w-10"></th>
            </tr>
          </thead>
          <tbody>
            {BC_APPROVED_TEMPLATES.map(t => (
              <tr key={t.id} className="border-b border-neutral-100 last:border-0 cursor-pointer hover:bg-neutral-50" onClick={() => setTpl(t.id)}>
                <td className="px-5 py-3.5 text-neutral-800">{t.name}</td>
                <td className="px-2 py-3.5 text-neutral-600">{t.channel}</td>
                <td className="px-2 py-3.5 text-neutral-600">{t.updated}</td>
                <td className="px-2 py-3.5 text-neutral-600">{t.category}</td>
                <td className="px-2 py-3.5 text-neutral-600">{t.language}</td>
                <td className="px-2 py-3.5 text-green-600 font-medium">Approved</td>
                <td className="px-5 py-3.5">
                  <span className={`w-6 h-6 rounded-full flex items-center justify-center ${tpl === t.id ? 'bg-neutral-900 text-white' : 'border-2 border-neutral-300'}`}>{tpl === t.id && <Icon name="check" size={13} strokeWidth={3} />}</span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <h3 className="text-2xl font-bold mb-5">Message content</h3>
      <label className="block text-[14px] text-neutral-500 mb-1.5">Version name</label>
      <input placeholder="E.g. onboarding message 1" className="w-full h-14 px-5 text-[15px] border border-neutral-200 rounded-xl mb-4 focus:outline-none focus:border-neutral-400" />
      <label className="block text-[14px] text-neutral-500 mb-1.5">Subject</label>
      <input defaultValue="Welcome to Mereka Programme" className="w-full h-14 px-5 text-[15px] border border-neutral-200 rounded-xl mb-4 focus:outline-none focus:border-neutral-400" />
      <label className="block text-[14px] text-neutral-500 mb-1.5">Preheader</label>
      <input defaultValue="Your learning journey starts here – brochure inside…" className="w-full h-14 px-5 text-[15px] border border-neutral-200 rounded-xl mb-4 focus:outline-none focus:border-neutral-400" />
      <div className="flex items-center justify-between mb-1.5">
        <label className="text-[14px] text-neutral-500">Message Body</label>
        <button className="h-8 px-3 border border-neutral-200 rounded-lg text-[13px] font-medium hover:bg-neutral-50">Add variable</button>
      </div>
      <textarea rows={5} defaultValue="'prefilled message from template'" className="w-full px-5 py-3.5 text-[15px] border border-neutral-200 rounded-xl resize-none focus:outline-none focus:border-neutral-400" />
      <p className="text-[13px] text-neutral-400 mt-2 flex items-center gap-2 flex-wrap">Use variables:
        <code className="px-1.5 py-0.5 bg-neutral-100 rounded">{'{{name}}'}</code>
        <code className="px-1.5 py-0.5 bg-neutral-100 rounded">{'{{email}}'}</code>
        <code className="px-1.5 py-0.5 bg-neutral-100 rounded">{'{{program_name}}'}</code>
      </p>
    </>
  );
}

/* ===== Preview ===== */
function BcPreviewStep() {
  return (
    <>
      <h1 className="text-3xl font-bold mb-6">Preview</h1>
      <div className="min-h-[420px]" />
    </>
  );
}

/* ===== Schedule ===== */
function BcScheduleStep() {
  const [when, setWhen] = useState('later');
  return (
    <>
      <h1 className="text-3xl font-bold">Schedule</h1>
      <p className="text-[15px] text-neutral-500 mt-1 mb-7">Schedule when to send out your message</p>

      <label className="block text-[15px] font-bold mb-3">When do you want to send out your message?</label>
      <div className="space-y-3 mb-7">
        <BcSelectRow label="Send immediately" checked={when === 'now'} onClick={() => setWhen('now')} />
        <BcSelectRow label="Schedule for later" checked={when === 'later'} onClick={() => setWhen('later')} />
      </div>

      {when === 'later' && (
        <>
          <label className="block text-[15px] font-bold mb-3">Schedule date &amp; time</label>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-7">
            <input type="date" className="h-14 px-5 text-[15px] border border-neutral-200 rounded-xl focus:outline-none focus:border-neutral-400" />
            <input type="time" className="h-14 px-5 text-[15px] border border-neutral-200 rounded-xl focus:outline-none focus:border-neutral-400" />
          </div>
        </>
      )}

      <label className="block text-[15px] font-bold mb-3">Summary</label>
      <div className="rounded-2xl border border-blue-200 bg-blue-50/50 p-5 space-y-2.5">
        <p className="text-[15px]"><span className="text-neutral-500">Template:</span> <span className="font-bold ml-2">Onboarding message_1</span></p>
        <p className="text-[15px]"><span className="text-neutral-500">Recipients :</span> <span className="font-semibold text-blue-600 ml-2">45</span></p>
        <p className="text-[15px]"><span className="text-neutral-500">Channel :</span> <span className="font-bold ml-2">Email</span></p>
        <p className="text-[15px]"><span className="text-neutral-500">Timing :</span> <span className="font-bold ml-2">Send at <span className="text-blue-600">04/05/2026 20:00</span></span></p>
      </div>
    </>
  );
}

Object.assign(window, { CreateMessageWizardPage });
