/* Mereka v2 — Broadcast template builder (Create blast message template) — Figma rebuild */

function BcSelectRow({ label, checked, onClick }) {
  return (
    <button onClick={onClick} className="w-full flex items-center justify-between h-14 px-5 border border-neutral-200 rounded-xl text-left hover:border-neutral-300 transition-colors">
      <span className="text-[16px] text-neutral-900">{label}</span>
      <span className={`w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0 ${checked ? 'bg-neutral-900 text-white' : 'border-2 border-neutral-300'}`}>
        {checked && <Icon name="check" size={14} strokeWidth={3} />}
      </span>
    </button>
  );
}

function BcSelect({ value, placeholder, options, 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-xl border border-neutral-100 py-1.5 z-30" style={{ boxShadow: '0 14px 36px rgba(0,0,0,0.13)' }}>
          {options.map(o => (
            <button key={o} onClick={() => { onChange(o); setOpen(false); }} className="w-full text-left px-5 py-2.5 text-[15px] text-neutral-800 hover:bg-neutral-50">{o}</button>
          ))}
        </div>
      )}
    </div>
  );
}

const BC_HEADER_TYPES = [
  { v: 'Text', icon: 'edit' }, { v: 'Image', icon: 'image' }, { v: 'Video', icon: 'video' },
  { v: 'Document', icon: 'document' }, { v: 'Location', icon: 'pin' },
];
const BC_BUTTON_TYPES = ['None', 'URL', 'Phone', 'Call on Whatsapp', 'Coupon Code'];

/* ===== WhatsApp preview ===== */
function BcWhatsAppPreview({ body, header, footer, hasButton }) {
  return (
    <div>
      <h3 className="text-lg font-bold mb-4">Preview</h3>
      <div className="rounded-2xl overflow-hidden border border-neutral-200" style={{ background: '#e5ddd5' }}>
        <div className="flex items-center gap-3 px-4 py-3" style={{ background: '#f0f2f5' }}>
          <Icon name="chevronLeft" size={18} className="text-neutral-500" />
          <div className="w-9 h-9 rounded-full bg-neutral-900 flex items-center justify-center"><img src="/mereka-logo-white.svg" alt="" style={{ width: 20 }} /></div>
          <div className="leading-tight">
            <p className="text-sm font-semibold flex items-center gap-1">mereka <span className="text-green-600">●</span></p>
            <p className="text-[12px] text-neutral-500">tap here for contact info</p>
          </div>
          <div className="ml-auto flex items-center gap-3 text-neutral-500"><Icon name="video" size={16} /><Icon name="phone" size={15} /></div>
        </div>
        <div className="p-4" style={{ backgroundImage: 'radial-gradient(rgba(0,0,0,0.04) 1px, transparent 1px)', backgroundSize: '16px 16px', minHeight: 380 }}>
          <p className="text-center text-[12px] text-neutral-500 mb-3">Fri, Apr 24</p>
          <div className="bg-white rounded-lg p-2.5 max-w-[88%] shadow-sm">
            {header === 'Image' && <div className="w-full h-28 rounded-md mb-2" style={{ background: 'repeating-conic-gradient(#111 0% 25%, #fff 0% 50%) 0 0 / 22px 22px' }} />}
            {header === 'Text' && <p className="text-[14px] font-bold mb-1">Header goes here</p>}
            <p className="text-[14px] text-neutral-800 leading-snug whitespace-pre-wrap">{body || 'Message goes here'}</p>
            {footer && <p className="text-[12px] text-neutral-400 mt-1">{footer}</p>}
            <p className="text-[11px] text-neutral-400 text-right mt-1">10:21</p>
            {hasButton && <div className="border-t border-neutral-100 mt-2 pt-2 text-center text-[14px] text-[#2563eb] font-medium">Call Us</div>}
          </div>
        </div>
        <div className="flex items-center gap-2 px-3 py-2.5" style={{ background: '#f0f2f5' }}>
          <Icon name="plus" size={18} className="text-neutral-500" />
          <div className="flex-1 h-9 bg-white rounded-full" />
          <Icon name="camera" size={16} className="text-neutral-500" />
        </div>
      </div>
    </div>
  );
}

/* ===== Template builder ===== */
function BcTemplateBuilderPage() {
  const [step, setStep] = useState('edit'); // 'edit' | 'preview'
  const [channel, setChannel] = useState('Whatsapp');
  const [name, setName] = useState('');
  const [category, setCategory] = useState('');
  const [language, setLanguage] = useState('');
  const [subject, setSubject] = useState('');
  const [preheader, setPreheader] = useState('');
  const [body, setBody] = useState('');
  const [headerOn, setHeaderOn] = useState(true);
  const [headerType, setHeaderType] = useState('Image');
  const [footerOn, setFooterOn] = useState(true);
  const [footer, setFooter] = useState('');
  const [buttonOn, setButtonOn] = useState(true);
  const [buttonMode, setButtonMode] = useState('cta'); // 'cta' | 'quick'
  const isWhatsapp = channel === 'Whatsapp';

  return (
    <DashShell active="/app/dashboard/communication-logs">
      <div className="flex items-center justify-between mb-5">
        <Link to="/app/dashboard/communication-logs" className="inline-flex items-center gap-2 text-[15px] font-medium text-neutral-700 hover:text-neutral-900">
          <Icon name="chevronLeft" size={20} /> Back
        </Link>
        <div className="flex items-center gap-2">
          <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="save" size={15} /> Save as draft</button>
          <button className="inline-flex items-center gap-2 h-10 px-4 border border-red-200 text-red-600 rounded-lg text-sm font-medium bg-white hover:bg-red-50"><Icon name="trash" size={15} /> Discard</button>
        </div>
      </div>

      <div className={`grid ${isWhatsapp && step === 'edit' ? 'grid-cols-1 xl:grid-cols-[1fr_380px]' : 'grid-cols-1'} gap-6`}>
        <div className="bg-white border border-neutral-200 rounded-2xl p-7">
          {step === 'preview' ? (
            <>
              <h2 className="text-2xl font-bold mb-6">Preview</h2>
              <div className="min-h-[420px] rounded-xl" />
            </>
          ) : (
            <>
              <h2 className="text-2xl font-bold mb-6">Create blast message template</h2>

              <label className="block text-[15px] font-bold mb-2">Template Name</label>
              <input value={name} onChange={e => setName(e.target.value)} placeholder="E.g. onboarding message"
                className="w-full h-14 px-5 text-[15px] border border-neutral-200 rounded-xl mb-5 focus:outline-none focus:border-neutral-400" />

              <label className="block text-[15px] font-bold mb-2">Category</label>
              <div className="mb-5"><BcSelect value={category} placeholder="Select category" onChange={setCategory} options={['Onboarding', 'Marketing', 'Reminder', 'Programme', 'Experience']} /></div>

              <label className="block text-[15px] font-bold mb-2">Language</label>
              <div className="mb-5"><BcSelect value={language} placeholder="Select language" onChange={setLanguage} options={['English', 'Malay', 'Chinese', 'Tamil']} /></div>

              <label className="block text-[15px] font-bold mb-2">Label (optional)</label>
              <input placeholder="Add labels" className="w-full h-14 px-5 text-[15px] border border-neutral-200 rounded-xl mb-6 focus:outline-none focus:border-neutral-400" />

              <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-6">Messages sent via WhatsApp will only be delivered to recipients with an active WhatsApp account.</p>

              {isWhatsapp && (
                <div className="rounded-xl border border-blue-200 bg-blue-50 px-5 py-4 mb-6">
                  <p className="text-[15px] font-bold text-blue-700">WhatsApp Template Approval Required</p>
                  <p className="text-[14px] text-blue-600 mt-0.5">WhatsApp templates must be approved by Meta before use. This typically takes 24-48 hours.</p>
                </div>
              )}

              <h3 className="text-[17px] font-bold mb-4">Message content</h3>
              {!isWhatsapp && (
                <>
                  <label className="block text-[14px] text-neutral-500 mb-1.5">Subject</label>
                  <input value={subject} onChange={e => setSubject(e.target.value)} placeholder="Type your subject here..."
                    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 value={preheader} onChange={e => setPreheader(e.target.value)} placeholder="Type your preheader here..."
                    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 value={body} onChange={e => setBody(e.target.value)} rows={5} placeholder="Type your message here..."
                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>

              {isWhatsapp && (
                <div className="mt-7">
                  <h3 className="text-[17px] font-bold mb-4">Optional content</h3>

                  {/* Header */}
                  <label className="flex items-center gap-2.5 mb-3 cursor-pointer">
                    <span onClick={() => setHeaderOn(v => !v)} className={`w-6 h-6 rounded-md flex items-center justify-center ${headerOn ? 'bg-neutral-900 text-white' : 'border-2 border-neutral-300'}`}>{headerOn && <Icon name="check" size={14} strokeWidth={3} />}</span>
                    <span className="text-[15px] font-semibold">Header</span>
                  </label>
                  {headerOn && (
                    <div className="mb-5">
                      <div className="flex items-center gap-2 mb-3 flex-wrap">
                        {BC_HEADER_TYPES.map(h => (
                          <button key={h.v} onClick={() => setHeaderType(h.v)} className={`h-9 px-4 rounded-lg text-sm font-medium transition-colors ${headerType === h.v ? 'bg-neutral-900 text-white' : 'bg-white border border-neutral-200 text-neutral-700 hover:bg-neutral-50'}`}>{h.v}</button>
                        ))}
                      </div>
                      {headerType === 'Text' ? (
                        <input placeholder="Header text" className="w-full h-12 px-4 text-[15px] border border-neutral-200 rounded-lg focus:outline-none focus:border-neutral-400" />
                      ) : (
                        <>
                          <button className="w-full h-12 px-4 border border-neutral-200 rounded-lg flex items-center justify-between text-[15px] text-neutral-400 hover:bg-neutral-50">Insert pdf or png <Icon name="upload" size={16} className="text-neutral-500" /></button>
                          <p className="text-[12px] text-neutral-400 mt-1">5mb max</p>
                        </>
                      )}
                    </div>
                  )}

                  {/* Footer */}
                  <label className="flex items-center gap-2.5 mb-3 cursor-pointer">
                    <span onClick={() => setFooterOn(v => !v)} className={`w-6 h-6 rounded-md flex items-center justify-center ${footerOn ? 'bg-neutral-900 text-white' : 'border-2 border-neutral-300'}`}>{footerOn && <Icon name="check" size={14} strokeWidth={3} />}</span>
                    <span className="text-[15px] font-semibold">Footer</span>
                  </label>
                  {footerOn && (
                    <input value={footer} onChange={e => setFooter(e.target.value)} placeholder="Add footer text" className="w-full h-12 px-4 text-[15px] border border-neutral-200 rounded-lg mb-5 focus:outline-none focus:border-neutral-400" />
                  )}

                  {/* Button */}
                  <label className="flex items-center gap-2.5 mb-3 cursor-pointer">
                    <span onClick={() => setButtonOn(v => !v)} className={`w-6 h-6 rounded-md flex items-center justify-center ${buttonOn ? 'bg-neutral-900 text-white' : 'border-2 border-neutral-300'}`}>{buttonOn && <Icon name="check" size={14} strokeWidth={3} />}</span>
                    <span className="text-[15px] font-semibold">Button</span>
                  </label>
                  {buttonOn && (
                    <>
                      <div className="flex items-center gap-2 mb-4">
                        <button onClick={() => setButtonMode('cta')} className={`h-9 px-4 rounded-lg text-sm font-medium ${buttonMode === 'cta' ? 'bg-neutral-900 text-white' : 'bg-white border border-neutral-200 text-neutral-700'}`}>Call to action</button>
                        <button onClick={() => setButtonMode('quick')} className={`h-9 px-4 rounded-lg text-sm font-medium ${buttonMode === 'quick' ? 'bg-neutral-900 text-white' : 'bg-white border border-neutral-200 text-neutral-700'}`}>Quick reply</button>
                      </div>
                      <BcButtonRow />
                      <BcButtonRow />
                    </>
                  )}
                </div>
              )}
            </>
          )}
        </div>

        {isWhatsapp && step === 'edit' && (
          <div className="bg-white border border-neutral-200 rounded-2xl p-6 h-fit">
            <BcWhatsAppPreview body={body} header={headerOn ? headerType : null} footer={footerOn ? footer : ''} hasButton={buttonOn} />
          </div>
        )}
      </div>

      {/* Footer actions */}
      <div className="bg-white border border-neutral-200 rounded-2xl px-7 py-5 mt-6 flex items-center justify-between">
        {step === 'edit' ? (
          <>
            <Link to="/app/dashboard/communication-logs"><button className="h-12 px-8 rounded-full border border-neutral-300 text-[15px] font-semibold hover:bg-neutral-50">Cancel</button></Link>
            {isWhatsapp ? (
              <button onClick={() => setStep('preview')} className="h-12 px-8 rounded-full bg-neutral-900 text-white text-[15px] font-semibold hover:bg-neutral-800">Submit template</button>
            ) : (
              <button onClick={() => setStep('preview')} className="h-12 px-8 rounded-full bg-neutral-900 text-white text-[15px] font-semibold hover:bg-neutral-800">Continue</button>
            )}
          </>
        ) : (
          <>
            <button onClick={() => setStep('edit')} className="h-12 px-8 rounded-full border border-neutral-300 text-[15px] font-semibold hover:bg-neutral-50">Cancel</button>
            <button className="h-12 px-8 rounded-full bg-neutral-900 text-white text-[15px] font-semibold hover:bg-neutral-800">Save template</button>
          </>
        )}
      </div>
    </DashShell>
  );
}

function BcButtonRow() {
  const [type, setType] = useState('None');
  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="grid grid-cols-1 lg:grid-cols-[180px_1fr] gap-3 items-center mb-3">
      <div className="relative" ref={ref}>
        <button onClick={() => setOpen(o => !o)} className="w-full h-12 px-4 border border-neutral-200 rounded-lg flex items-center justify-between text-[15px] hover:border-neutral-300">
          {type} <Icon name="chevronDown" size={16} className="text-neutral-500" />
        </button>
        {open && (
          <div className="absolute left-0 top-[calc(100%+6px)] w-full bg-white rounded-xl border border-neutral-100 py-1.5 z-30" style={{ boxShadow: '0 14px 36px rgba(0,0,0,0.13)' }}>
            {BC_BUTTON_TYPES.map(o => <button key={o} onClick={() => { setType(o); setOpen(false); }} className="w-full text-left px-4 py-2.5 text-[15px] hover:bg-neutral-50">{o}</button>)}
          </div>
        )}
      </div>
      <div className="flex items-center gap-2">
        <span className="text-[14px] text-neutral-500 whitespace-nowrap">Button text</span>
        <input placeholder="Please select an option" className="flex-1 h-12 px-4 text-[15px] border border-neutral-200 rounded-lg focus:outline-none focus:border-neutral-400" />
      </div>
    </div>
  );
}

Object.assign(window, { BcTemplateBuilderPage, BcSelectRow });
