/* ============================================================
   Student — Social media checklist
   Port of the previous social-media portal, now as a module
   inside the dashboard. Brands × platforms grid + review.
   ============================================================ */

function StudentSocial({ ctx, rec }) {
  const { setToast } = ctx;
  const s = rec.social;
  const [tab, setTab] = useState('follow');

  const set = (patcher) => window.Store.patchStudent(rec.id, (r) => {
    patcher(r.social); return r;
  });

  // counts
  const required = ['instagram','youtube','facebook'];
  const reqTotal = window.BRANDS.length * required.length;
  const reqDone = window.BRANDS.reduce((sum, b) => sum + required.filter(p => s.follows[b.id]?.[p]).length, 0);
  const liDone = window.BRANDS.filter(b => s.follows[b.id]?.linkedin).length;

  const submit = () => {
    if (reqDone < reqTotal) return setToast(`Complete all required follows (${reqDone}/${reqTotal})`);
    if (s.review.submitted !== 'yes') return setToast('Confirm you have submitted your review');
    if (!s.signatures.student) return setToast('Add your signature first');
    set(soc => {
      soc.status = 'submitted';
      soc.submittedAt = new Date().toISOString();
      soc.refNumber = soc.refNumber || `IDA-SMC-${Date.now().toString(36).toUpperCase().slice(-6)}`;
    });
    setToast('Submitted to office for verification');
  };

  return (
    <div className="module">
      <ModuleHeader
        crumbs={`MODULE 7 OF 8 · SOCIAL MEDIA CHECKLIST`}
        title={tr("Social media checklist")}
        sub={tr("Final-day commitment to engage with the IDA family. Follow on all required platforms, submit a short review, get countersigned.")}
        right={
          <div className="row" style={{gap:8}}>
            <div className="pill pill-good"><i className="dotty"/>{reqDone}/{reqTotal} {tr('required')}</div>
            <div className="pill pill-info"><i className="dotty"/>{liDone}/{window.BRANDS.length} LinkedIn</div>
            <StatusPill status={s.status}/>
          </div>
        }
      />

      <div className="tabs">
        {[
          { id:'follow', lbl:'Follow & subscribe',  c: `${reqDone}/${reqTotal}` },
          { id:'review', lbl:'Review & share',      c: [s.review.submitted, s.review.sharedToBatch, s.review.sharedToEmployee].filter(v => v === 'yes').length + '/3' },
          { id:'verify', lbl:'Verification & signatures', c: s.status === 'verified' ? '✓' : '·' },
        ].map(t => (
          <button key={t.id} className={cls('tab', tab===t.id && 'active')} onClick={()=>setTab(t.id)}>
            {tr(t.lbl)}<span className="count">{t.c}</span>
          </button>
        ))}
      </div>

      {tab === 'follow' && (
        <div className="grid g-side">
          <div className="stack">
            <div className="card">
              <div className="card-hd">
                <div><h3>{tr('Brands & platforms')}</h3><div className="sub">{tr('Tap a platform to toggle. Instagram, YouTube and Facebook are required for all brands.')}</div></div>
              </div>
              <div className="card-body" style={{padding:0}}>
                {window.BRANDS.map(b => (
                  <BrandRow key={b.id} brand={b}
                            state={s.follows[b.id] || {}}
                            onToggle={(p) => set(soc => {
                              soc.follows[b.id] = { ...soc.follows[b.id], [p]: !soc.follows[b.id]?.[p] };
                            })}
                            disabled={s.status === 'verified'}/>
                ))}
              </div>
            </div>
          </div>
          <div className="stack">
            <div className="card">
              <div className="card-hd"><h3>{tr('Why this matters')}</h3></div>
              <div className="card-body small muted" style={{lineHeight:1.6}}>
                <p style={{margin:'0 0 8px'}}>{tr("India Drone Academy's WhatsApp, social and YouTube channels are how the alumni community stays in touch. Following keeps you in the loop for job postings, alumni events and DGCA updates.")}</p>
                <p style={{margin:0}}>{tr('Take this seriously — your certificate is contingent on it.')}</p>
              </div>
            </div>
            <div className="card">
              <div className="card-hd"><h3>{tr('Progress')}</h3></div>
              <div className="card-body">
                <div style={{textAlign:'center',padding:'4px 0 16px'}}>
                  <Donut value={Math.round((reqDone/reqTotal)*100)} size={120} stroke={10} sub="required"/>
                </div>
                <div className="stack-sm">
                  <RowStat lbl="Required follows" v={`${reqDone}/${reqTotal}`}/>
                  <RowStat lbl="Optional · LinkedIn" v={`${liDone}/${window.BRANDS.length}`}/>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {tab === 'review' && (
        <div className="grid g-side">
          <div className="stack">
            <div className="card">
              <div className="card-hd">
                <div><h3>{tr('Did you submit a review?')}</h3><div className="sub">{tr('Google Business listing for India Drone Academy.')}</div></div>
              </div>
              <div className="card-body stack-sm">
                <YesNoRow label="I have submitted a review on the Google business page"
                  v={s.review.submitted} on={v => set(soc => soc.review.submitted = v)}
                  disabled={s.status === 'verified'}/>
                <YesNoRow label="I have shared the IDA WhatsApp invite with my batch"
                  v={s.review.sharedToBatch} on={v => set(soc => soc.review.sharedToBatch = v)}
                  disabled={s.status === 'verified'}/>
                <YesNoRow label="I have shared the social handles with my employee group"
                  v={s.review.sharedToEmployee} on={v => set(soc => soc.review.sharedToEmployee = v)}
                  disabled={s.status === 'verified'}/>
              </div>
            </div>

            <div className="card">
              <div className="card-hd">
                <div><h3>{tr('Optional — proof screenshots')}</h3><div className="sub">{tr("Helpful if you'd like to skip the manual verification step.")}</div></div>
              </div>
              <div className="card-body">
                <div className="row-wrap" style={{marginBottom:10}}>
                  {(s.review.screenshots || []).map((f,i) => (
                    <FileChip key={i} file={f}
                      onRemove={s.status === 'verified' ? null : () => set(soc => soc.review.screenshots.splice(i,1))}/>
                  ))}
                </div>
                {s.status !== 'verified' && (
                  <FileDrop multiple studentId={rec.id} docId="social"
                    hint={tr('Up to 4 screenshots · PNG / JPG')}
                    onFiles={(files) => set(soc => soc.review.screenshots = [...(soc.review.screenshots || []), ...files])}/>
                )}
              </div>
            </div>
          </div>

          <div className="stack">
            <div className="card">
              <div className="card-hd"><h3>{tr('Google Business link')}</h3></div>
              <div className="card-body">
                <a className="btn btn-sm"
                   href="https://www.google.com/maps/place/India+Drone+Academy"
                   target="_blank" rel="noopener">
                  {window.Icons.google({width:13,height:13})} {tr('Open in Google Maps')}
                </a>
                <p className="small muted" style={{margin:'10px 0 0',lineHeight:1.55}}>
                  {tr("Submit a star rating and a 1–2 line review. Mention what you learned, who taught you and whether you'd recommend the school.")}
                </p>
              </div>
            </div>
          </div>
        </div>
      )}

      {tab === 'verify' && (
        <div className="grid g-side">
          <div className="stack">
            {s.status === 'verified' ? (
              <div className="banner good">
                <div className="body"><b>{tr('Verified.')}</b> {tr('by')} {s.verify.empName || 'IDA Office'} {tr('on')} {UI.fmtDate(s.verifiedAt)} · {tr('Ref.')} {s.refNumber}</div>
              </div>
            ) : s.status === 'submitted' ? (
              <div className="banner warn">
                <div className="body"><b>{tr('Submitted.')}</b> {tr('Awaiting office verification — typically within one working day.')}</div>
              </div>
            ) : (
              <div className="banner">
                <div className="body">{tr("Complete the items above, sign below and submit. You'll be notified once an employee verifies your submission.")}</div>
              </div>
            )}

            <div className="card">
              <div className="card-hd">
                <div><h3>{tr('Office verification')}</h3><div className="sub">{tr('Read-only — filled by the verifying employee.')}</div></div>
              </div>
              <div className="card-body">
                <div className="grid g-2">
                  {[
                    { id:'followed',       lbl:'Followed all required platforms' },
                    { id:'submitted',      lbl:'Review submitted' },
                    { id:'googleSubmitted',lbl:'Google review verified' },
                    { id:'verified',       lbl:'WhatsApp / batch share verified' },
                    { id:'signed',         lbl:'Student signed' },
                  ].map(item => {
                    const v = s.verify.items[item.id];
                    return (
                      <div key={item.id} style={{padding:'10px 12px',background:'var(--bg)',
                        borderRadius:8,border:'1px solid var(--line)'}}>
                        <div className="row" style={{justifyContent:'space-between'}}>
                          <span className="small">{tr(item.lbl)}</span>
                          {v?.status === 'ok' && <span className="pill pill-good">{tr('OK')}</span>}
                          {v?.status === 'returned' && <span className="pill pill-bad">{tr('Returned')}</span>}
                          {!v?.status && <span className="pill pill-ghost">{tr('Pending')}</span>}
                        </div>
                        {v?.remark && <div className="tiny muted" style={{marginTop:4}}>{v.remark}</div>}
                      </div>
                    );
                  })}
                </div>
                {s.verify.returnedReason && (
                  <div className="banner bad" style={{marginTop:12}}>
                    <div className="body"><b>{tr('Returned')}:</b> {s.verify.returnedReason}</div>
                  </div>
                )}
              </div>
            </div>

            <div className="card">
              <div className="card-hd"><h3>{tr('Signatures')}</h3></div>
              <div className="card-body grid g-3">
                <SignaturePad label={tr('Student')} role={rec.profile.fullName}
                  value={s.signatures.student}
                  onChange={(v) => set(soc => soc.signatures.student = v)}
                  disabled={s.status === 'verified'}/>
                <div>
                  <div className="tiny upper muted" style={{marginBottom:8,fontWeight:600}}>
                    {tr('Verifying employee')} — {s.verify.empName || tr('pending')}
                  </div>
                  <div className="sig-pad signed" style={{height:100}}>
                    {s.signatures.employee ?
                      <div style={{padding:'8px 12px',fontSize:11,color:'var(--muted)',fontFamily:'var(--font-mono)'}}>✓ {tr('Signed by')} {s.verify.empName}</div> :
                      <div className="ph">{tr('Awaiting employee')}</div>
                    }
                  </div>
                </div>
                <div>
                  <div className="tiny upper muted" style={{marginBottom:8,fontWeight:600}}>{tr('Authorised signatory')}</div>
                  <div className="sig-pad signed" style={{height:100}}>
                    {s.signatures.authorized ?
                      <div style={{padding:'8px 12px',fontSize:11,color:'var(--muted)',fontFamily:'var(--font-mono)'}}>✓ {tr('Signed')}</div> :
                      <div className="ph">{tr('Awaiting authorised signatory')}</div>
                    }
                  </div>
                </div>
              </div>
              <div className="card-foot">
                <div>{tr('Reference number')} · <span className="mono">{s.refNumber || '—'}</span></div>
                <div className="row" style={{gap:8}}>
                  {s.status !== 'verified' && (
                    <button className="btn btn-primary btn-sm" onClick={submit}>
                      {s.status === 'submitted' ? tr('Re-submit') : tr('Submit for verification')}
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>

          <div className="stack">
            <div className="card">
              <div className="card-hd"><h3>{tr('Status')}</h3></div>
              <div className="card-body">
                <Timeline items={[
                  { label:tr('Started checklist'), ts: rec.createdAt, done: true },
                  { label:tr('Submitted'), ts: s.submittedAt, done: !!s.submittedAt },
                  { label:tr('Verified'), ts: s.verifiedAt, done: !!s.verifiedAt },
                ]}/>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function BrandRow({ brand, state, onToggle, disabled }) {
  const Icons = window.Icons;
  return (
    <div className="brand-row">
      <div className="brand-mark">{brand.name[0]}</div>
      <div>
        <div className="nm">{brand.name}</div>
        <div className="tag">{brand.tag}</div>
      </div>
      <div className="platforms">
        {window.PLATFORMS.map(p => (
          <button key={p.id} className={cls('platform-btn', state[p.id] && 'done')}
                  disabled={disabled}
                  onClick={() => {
                    if (!state[p.id]) window.open(brand.links[p.id], '_blank', 'noopener');
                    onToggle(p.id);
                  }}>
            <span className="ico">{Icons[p.cls]?.()}</span>
            <span>{p.short}</span>
            {state[p.id] && <span style={{marginLeft:4}}>{Icons.check({width:9,height:9})}</span>}
          </button>
        ))}
      </div>
    </div>
  );
}

function YesNoRow({ label, v, on, disabled }) {
  return (
    <div className="row" style={{justifyContent:'space-between', padding:'8px 0',
      borderBottom:'1px solid var(--line)'}}>
      <span className="small" style={{flex:1}}>{tr(label)}</span>
      <div className="row" style={{gap:6}}>
        <button className={cls('btn btn-xs', v==='yes' ? 'btn-primary' : '')}
                disabled={disabled} onClick={()=>on('yes')}>{tr('Yes')}</button>
        <button className={cls('btn btn-xs', v==='no' ? 'btn-bad' : '')}
                disabled={disabled} onClick={()=>on('no')}>{tr('No')}</button>
        <button className={cls('btn btn-xs', !v ? 'btn-ghost' : 'btn-ghost')}
                style={!v ? {opacity:.4} : {}}
                disabled={disabled} onClick={()=>on(null)}>—</button>
      </div>
    </div>
  );
}

function RowStat({ lbl, v }) {
  return (
    <div className="row" style={{justifyContent:'space-between',padding:'4px 0'}}>
      <span className="small muted">{tr(lbl)}</span>
      <span className="mono small">{v}</span>
    </div>
  );
}
window.RowStat = RowStat;

window.StudentSocial = StudentSocial;
