/* Media Plan module =================================================
   Account-linked. Two ingestion paths, both previewed in-app:
   • File upload — PDF (in-app viewer) / CSV / XLSX (rendered as table)
   • Google Sheets URL — embedded interactive iframe
   Upload/link tools are RBAC-gated (super_admin + admin only).
=================================================================== */

const MEDIA_LS = 'relay_media_plans_v1';
function loadMediaPlans(){ return loadLS(MEDIA_LS, {}); }
function saveMediaPlan(accountId, plan){
  const all = loadMediaPlans();
  if (plan) all[accountId] = plan; else delete all[accountId];
  saveLS(MEDIA_LS, all);
  return all;
}

/* Convert a Google Sheets edit/view URL into an embeddable preview URL */
function toSheetEmbed(url){
  try {
    if (/\/pubhtml|\/preview|output=embed/.test(url)) return url;
    return url.replace(/\/edit.*$/, '/preview').replace(/\/view.*$/, '/preview');
  } catch(e){ return url; }
}

/* Parse a CSV/XLSX File into { cols, rows } via SheetJS */
function parseSheetFile(file){
  return new Promise((resolve, reject)=>{
    const reader = new FileReader();
    reader.onload = (e)=>{
      try {
        const data = new Uint8Array(e.target.result);
        const wb = XLSX.read(data, { type:'array' });
        const ws = wb.Sheets[wb.SheetNames[0]];
        const arr = XLSX.utils.sheet_to_json(ws, { header:1, blankrows:false, defval:'' });
        const cols = (arr[0]||[]).map(c=>String(c));
        const rows = arr.slice(1).map(r=>cols.map((_,i)=> r[i]==null?'':r[i]));
        resolve({ cols, rows, sheetNames: wb.SheetNames });
      } catch(err){ reject(err); }
    };
    reader.onerror = reject;
    reader.readAsArrayBuffer(file);
  });
}
function readAsDataURL(file){
  return new Promise((res,rej)=>{ const r=new FileReader(); r.onload=e=>res(e.target.result); r.onerror=rej; r.readAsDataURL(file); });
}

/* ---------- Sheet table preview ------------------------------------ */
function SheetTable({ cols, rows }){
  if (!cols || !cols.length) return <div className="p-8 text-center text-[13px] text-ink-400">Empty sheet.</div>;
  return (
    <div className="overflow-auto scroll-soft max-h-[560px]">
      <table className="w-full border-collapse text-[12.5px]">
        <thead className="sticky top-0 z-[1]">
          <tr>
            <th className="sticky left-0 z-[2] bg-ink-100 dark:bg-ink-800 border border-ink-200 dark:border-white/10 px-2 py-1.5 text-[10px] font-mono text-ink-400 w-10"></th>
            {cols.map((c,i)=>(
              <th key={i} className="bg-ink-100 dark:bg-ink-800 border border-ink-200 dark:border-white/10 px-3 py-1.5 text-left font-semibold whitespace-nowrap">{c||<span className="text-ink-400 font-mono">{String.fromCharCode(65+i)}</span>}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((r,ri)=>(
            <tr key={ri} className="hover:bg-accent-50/40 dark:hover:bg-white/[0.03]">
              <td className="sticky left-0 z-[1] bg-ink-50 dark:bg-ink-900 border border-ink-200 dark:border-white/10 px-2 py-1.5 text-[10px] font-mono text-ink-400 text-center">{ri+1}</td>
              {r.map((cell,ci)=>{
                const num = typeof cell==='number' || (/^[$£€]?[\d,.]+%?$/.test(String(cell)) && String(cell).trim()!=='');
                return <td key={ci} className={`border border-ink-100 dark:border-white/5 px-3 py-1.5 whitespace-nowrap ${num?'text-right tabular font-mono':''}`}>{String(cell)}</td>;
              })}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* ---------- Upload / link empty state ------------------------------ */
function MediaPlanEmpty({ canManage, onFile, onLink, busy, error }){
  const fileRef = useRef(null);
  const [url, setUrl] = useState('');
  const [drag, setDrag] = useState(false);
  if (!canManage){
    return (
      <Card className="rounded-2xl p-12 text-center">
        <div className="w-14 h-14 mx-auto rounded-2xl bg-ink-100 dark:bg-white/5 grid place-items-center mb-3"><Icon name="info" size={24} className="text-ink-400"/></div>
        <div className="text-[15px] font-semibold">No media plan for this account yet</div>
        <div className="text-[13px] text-ink-500 dark:text-ink-300 mt-1">An Admin or Super Admin can upload a plan or link a Google Sheet here.</div>
      </Card>
    );
  }
  return (
    <div className="grid md:grid-cols-2 gap-3">
      <div
        onDragOver={e=>{e.preventDefault();setDrag(true);}} onDragLeave={()=>setDrag(false)}
        onDrop={e=>{e.preventDefault();setDrag(false); if(e.dataTransfer.files[0]) onFile(e.dataTransfer.files[0]);}}
        className={`rounded-2xl border-2 border-dashed p-8 text-center transition ${drag?'border-accent-400 bg-accent-50/60 dark:bg-accent-500/10':'border-ink-200 dark:border-white/15 bg-white dark:bg-ink-900/40'}`}>
        <div className="w-12 h-12 mx-auto rounded-xl bg-accent-100 dark:bg-accent-500/15 grid place-items-center mb-3"><Icon name="plus" size={22} className="text-accent-600 dark:text-accent-300"/></div>
        <div className="text-[14px] font-semibold">Upload a media plan</div>
        <div className="text-[12.5px] text-ink-500 dark:text-ink-300 mt-1 mb-4">Drag & drop or browse · PDF, CSV or XLSX</div>
        <input ref={fileRef} type="file" accept=".pdf,.csv,.xlsx,.xls" className="hidden" onChange={e=>e.target.files[0]&&onFile(e.target.files[0])}/>
        <Btn variant="accent" icon="plus" onClick={()=>fileRef.current.click()} disabled={busy}>{busy?'Reading…':'Choose file'}</Btn>
        <div className="flex items-center justify-center gap-2 mt-4 text-[11px] text-ink-400">
          {['pdf','csv','xlsx'].map(t=><span key={t} className="px-1.5 py-0.5 rounded bg-ink-100 dark:bg-white/5 font-mono uppercase">{t}</span>)}
        </div>
      </div>
      <div className="rounded-2xl border border-ink-200 dark:border-white/15 bg-white dark:bg-ink-900/40 p-8">
        <div className="w-12 h-12 rounded-xl bg-emerald-100 dark:bg-emerald-500/15 grid place-items-center mb-3"><Icon name="link" size={20} className="text-emerald-600 dark:text-emerald-300"/></div>
        <div className="text-[14px] font-semibold">Link a Google Sheet</div>
        <div className="text-[12.5px] text-ink-500 dark:text-ink-300 mt-1 mb-4">Paste a share URL — it embeds as an interactive sheet.</div>
        <input value={url} onChange={e=>setUrl(e.target.value)} placeholder="https://docs.google.com/spreadsheets/d/…"
          className="w-full h-10 px-3 rounded-xl border border-ink-200 dark:border-white/10 bg-white dark:bg-ink-900/60 text-[12.5px] font-mono focus:outline-none focus:border-accent-400 mb-3"/>
        <Btn variant="primary" icon="link" onClick={()=>url.trim()&&onLink(url.trim())} disabled={!url.trim()}>Embed sheet</Btn>
        <div className="text-[11px] text-ink-400 mt-3">Tip: set the sheet to “Anyone with the link can view”.</div>
      </div>
      {error && <div className="md:col-span-2 text-[12.5px] text-rose-600 dark:text-rose-300 bg-rose-50 dark:bg-rose-500/10 border border-rose-200 dark:border-rose-500/25 rounded-lg px-3 py-2 flex items-center gap-2"><Icon name="alert" size={14}/>{error}</div>}
    </div>
  );
}

/* ---------- The Media Plan view ------------------------------------ */
function MediaPlanView({ accountId, currentUser, canManage, pushAudit }){
  const [plan, setPlan] = useState(()=>loadMediaPlans()[accountId] || null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  useEffect(()=>{ setPlan(loadMediaPlans()[accountId]||null); setError(''); }, [accountId]);

  const acc = ACCOUNTS.find(a=>a.id===accountId);

  const commit = (p) => {
    setPlan(p); saveMediaPlan(accountId, p);
    if (pushAudit) pushAudit(currentUser, 'integration.update', `Media plan · ${acc.name}`, p?`${p.type.toUpperCase()} · ${p.title}`:'removed');
  };

  const onFile = async (file) => {
    setError(''); setBusy(true);
    try {
      const ext = (file.name.split('.').pop()||'').toLowerCase();
      if (ext==='pdf'){
        if (file.size > 8*1024*1024){ setError('PDF is over 8MB — too large to persist in the demo store. Use a smaller file or a Google Sheet link.'); setBusy(false); return; }
        const dataUrl = await readAsDataURL(file);
        commit({ type:'pdf', title:file.name.replace(/\.pdf$/i,''), fileName:file.name, dataUrl, uploadedBy:currentUser.name, uploadedAt:Date.now() });
      } else if (ext==='csv' || ext==='xlsx' || ext==='xls'){
        const { cols, rows } = await parseSheetFile(file);
        commit({ type: ext==='csv'?'csv':'xlsx', title:file.name.replace(/\.(csv|xlsx|xls)$/i,''), fileName:file.name, cols, rows, uploadedBy:currentUser.name, uploadedAt:Date.now() });
      } else {
        setError('Unsupported file type. Upload a PDF, CSV or XLSX.');
      }
    } catch(err){ setError('Could not read that file. '+(err.message||'')); }
    setBusy(false);
  };
  const onLink = (url) => {
    if (!/docs\.google\.com\/spreadsheets/.test(url)){ setError('That doesn’t look like a Google Sheets URL.'); return; }
    commit({ type:'gsheet', title:'Linked Google Sheet', url, embed:toSheetEmbed(url), uploadedBy:currentUser.name, uploadedAt:Date.now() });
  };

  const header = (
    <div className="flex items-center gap-3 mb-4">
      <span className="inline-flex items-center justify-center w-10 h-10 rounded-xl bg-accent-100 dark:bg-accent-500/15 text-accent-600 dark:text-accent-300"><Icon name="mediaplan" size={22}/></span>
      <div className="flex-1">
        <h1 className="text-[20px] font-semibold tracking-tight leading-none">Media Plan</h1>
        <div className="text-[12px] text-ink-500 dark:text-ink-300 mt-1">{acc.name} · {plan?`linked ${plan.type.toUpperCase()}`:'not set'}</div>
      </div>
    </div>
  );

  if (!plan){
    return <div>{header}<MediaPlanEmpty canManage={canManage} onFile={onFile} onLink={onLink} busy={busy} error={error}/></div>;
  }

  return (
    <div>
      {header}
      <Card className="rounded-2xl overflow-hidden">
        <div className="px-4 py-3 flex items-center gap-3 border-b border-ink-200 dark:border-white/10 flex-wrap">
          <Pill tone="accent" className="uppercase">{plan.type}</Pill>
          <div className="min-w-0 flex-1">
            <div className="text-[13px] font-semibold truncate">{plan.title}</div>
            <div className="text-[11px] text-ink-400 font-mono truncate">{plan.fileName||plan.url} · added by {plan.uploadedBy}</div>
          </div>
          {plan.type==='gsheet' && <a href={plan.url} target="_blank" rel="noreferrer"><Btn size="sm" variant="ghost" icon="link">Open</Btn></a>}
          {plan.type==='pdf' && <a href={plan.dataUrl} download={plan.fileName}><Btn size="sm" variant="ghost" icon="chev-down">Download</Btn></a>}
          {canManage && <>
            <label className="cursor-pointer">
              <input type="file" accept=".pdf,.csv,.xlsx,.xls" className="hidden" onChange={e=>e.target.files[0]&&onFile(e.target.files[0])}/>
              <span className="inline-flex items-center gap-1.5 h-8 px-3 rounded-lg text-[12.5px] font-medium border border-ink-200 dark:border-white/10 hover:bg-ink-50 dark:hover:bg-white/5 transition"><Icon name="settings" size={13}/>Replace</span>
            </label>
            <button onClick={()=>commit(null)} className="inline-flex items-center gap-1.5 h-8 px-3 rounded-lg text-[12.5px] font-medium text-rose-600 dark:text-rose-300 hover:bg-rose-50 dark:hover:bg-rose-500/10 transition"><Icon name="x" size={13}/>Remove</button>
          </>}
        </div>

        {plan.type==='pdf' && (
          <iframe title="Media plan PDF" src={plan.dataUrl} className="w-full" style={{height:640, border:0, background:'#fff'}}/>
        )}
        {plan.type==='gsheet' && (
          <iframe title="Media plan sheet" src={plan.embed} className="w-full" style={{height:640, border:0, background:'#fff'}}/>
        )}
        {(plan.type==='csv' || plan.type==='xlsx') && (
          <SheetTable cols={plan.cols} rows={plan.rows}/>
        )}
      </Card>
      {error && <div className="mt-3 text-[12.5px] text-rose-600 dark:text-rose-300 bg-rose-50 dark:bg-rose-500/10 border border-rose-200 dark:border-rose-500/25 rounded-lg px-3 py-2 flex items-center gap-2"><Icon name="alert" size={14}/>{error}</div>}
    </div>
  );
}

Object.assign(window, { MediaPlanView, loadMediaPlans, saveMediaPlan, toSheetEmbed, parseSheetFile, SheetTable });
