// WTS Cyprus — PBC: WTS-branded external Client Portal (F10)
// A separate, brand-isolated experience for the signed-in client contact.
const { useState: useStateP, useMemo: useMemoP, useEffect: useEffectP } = React;

// Signed-in client contact for the demo (Aegean Holdings — current + past engagements)
const PORTAL_USER = { name: 'Elena Markou', email: 'e.markou@aegeanholdings.com.cy', clientId: 'c1', role: 'Financial Controller' };

const hasValue = (type, v) => {
  if (v == null) return false;
  switch (type) {
    case 'file':        return (v.files || []).length > 0;
    case 'number':      return v.number !== '' && v.number != null;
    case 'currency':    return v.amount !== '' && v.amount != null;
    case 'date':        return !!v.date;
    case 'boolean':     return v.bool === true || v.bool === false;
    case 'multichoice': return !!v.choice;
    case 'freetext':    return !!(v.text && v.text.trim());
    case 'table':       return Array.isArray(v.rows) && v.rows.length > 0;
    default:            return false;
  }
};

// ── Type-aware input for the client ───────────────────────────────────────
const PortalInput = ({ item, value, onChange }) => {
  switch (item.type) {
    case 'file':
      return (
        <div>
          <button type="button" className="wts-dropzone" style={{ padding: '22px 18px' }}
            onClick={() => onChange({ files: [...((value && value.files) || []), `${item.label.replace(/[^A-Za-z0-9]+/g, '_').slice(0, 24)}_${(((value && value.files) || []).length + 1)}.pdf`] })}>
            <Icon name="upload-cloud" size={24} style={{ opacity: 0.5 }} />
            <div style={{ fontSize: 13, fontWeight: 500, marginTop: 8 }}>Click to attach a file</div>
            <div style={{ fontSize: 12, color: 'var(--muted-foreground)', marginTop: 2 }}>PDF, Excel or image · up to 50MB</div>
          </button>
          {value && value.files && value.files.length > 0 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
              {value.files.map((f, i) => (
                <span key={i} className="wts-attach-chip wts-attach-chip--lg"><Icon name="file" size={12} /> {f}
                  <button type="button" className="wts-chip-x" style={{ marginLeft: 2 }} onClick={() => onChange({ files: value.files.filter((_, j) => j !== i) })}><Icon name="x" size={10} /></button>
                </span>
              ))}
            </div>
          )}
        </div>
      );
    case 'number':
      return <Input type="number" placeholder="Enter a number" value={(value && value.number) ?? ''} onChange={e => onChange({ number: e.target.value })} style={{ maxWidth: 260 }} />;
    case 'currency':
      return (
        <div className="wts-currency-input" style={{ width: 'fit-content' }}>
          <span className="wts-currency-input__pre">{(value && value.currency) || 'EUR'}</span>
          <input className="wts-currency-input__input" style={{ width: 140, textAlign: 'left' }} type="number" placeholder="0" value={(value && value.amount) ?? ''} onChange={e => onChange({ amount: e.target.value, currency: 'EUR' })} />
        </div>
      );
    case 'date':
      return <input type="date" className="wts-input" style={{ maxWidth: 200 }} value={(value && value.date) || ''} onChange={e => onChange({ date: e.target.value })} />;
    case 'boolean':
      return (
        <div style={{ display: 'flex', gap: 8 }}>
          {[{ b: true, l: 'Yes' }, { b: false, l: 'No' }].map(o => (
            <button key={o.l} type="button" className={cn('wts-override__radio', value && value.bool === o.b && 'wts-override__radio--on accept')} style={{ flex: '0 0 auto', minWidth: 80 }} onClick={() => onChange({ bool: o.b })}>{o.l}</button>
          ))}
        </div>
      );
    case 'multichoice':
      return (
        <div className="wts-radio-group">
          {(item.options || []).map(opt => (
            <label key={opt} className="wts-radio">
              <input type="radio" name={item.id} checked={(value && value.choice) === opt} onChange={() => onChange({ choice: opt })} />
              <span>{opt}</span>
            </label>
          ))}
        </div>
      );
    case 'freetext':
      return <Textarea placeholder="Type your answer…" value={(value && value.text) || ''} onChange={e => onChange({ text: e.target.value })} style={{ minHeight: 90 }} />;
    case 'table': {
      const cols = item.columns || ['Column 1', 'Column 2'];
      const rows = (value && value.rows) || [];
      const setCell = (ri, ci, val) => { const nr = rows.map(r => r.slice()); nr[ri][ci] = val; onChange({ rows: nr }); };
      return (
        <div style={{ border: '1px solid var(--border)', borderRadius: 8, overflow: 'hidden' }}>
          <table className="ck-table" style={{ fontSize: 12.5 }}>
            <thead><tr>{cols.map(c => <th key={c}>{c}</th>)}</tr></thead>
            <tbody>
              {rows.map((r, ri) => (
                <tr key={ri}>{cols.map((_, ci) => (
                  <td key={ci} style={{ padding: 4 }}><input className="wts-input" style={{ height: 30, fontSize: 12.5, border: 0, boxShadow: 'none' }} value={r[ci] || ''} onChange={e => setCell(ri, ci, e.target.value)} /></td>
                ))}</tr>
              ))}
            </tbody>
          </table>
          <button type="button" className="wts-add-manual" style={{ margin: 8, border: 0 }} onClick={() => onChange({ rows: [...rows, cols.map(() => '')] })}>
            <Icon name="plus" size={12} /> Add row
          </button>
        </div>
      );
    }
    default: return null;
  }
};

// ── A single request item card in the portal ──────────────────────────────
const PortalItemCard = ({ item, onSubmit }) => {
  const [draft, setDraft] = useStateP(item.value || null);
  const [showComments, setShowComments] = useStateP(false);
  useEffectP(() => { setDraft(item.value || null); }, [item.id, item.status]);
  const meta = ITEM_TYPE_META[item.type];
  const editable = item.status === 'pending' || item.status === 'change_requested';
  const overdue = editable && isOverdue(item.deadline);

  return (
    <div className="wts-portal-item">
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <span className="wts-portal-item__type"><Icon name={meta.icon} size={15} style={{ opacity: 0.7 }} /></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-0.01em' }}>{item.label}</span>
            {item.required ? <span className="ck-badge ck-badge--outline" style={{ fontSize: 10 }}>Required</span> : <span style={{ fontSize: 11, color: 'var(--muted-foreground)' }}>Optional</span>}
            <div style={{ flex: 1 }} />
            <StatusBadge status={item.status} />
          </div>
          {item.description && <p style={{ fontSize: 13, color: 'var(--muted-foreground)', lineHeight: 1.55, margin: '6px 0 0' }}>{item.description}</p>}
          <div style={{ fontSize: 12, color: overdue ? 'var(--destructive)' : 'var(--muted-foreground)', marginTop: 6, fontWeight: overdue ? 500 : 400 }}>
            <Icon name="calendar" size={11} style={{ verticalAlign: '-1px', marginRight: 4, opacity: 0.6 }} />Due {formatDate(item.deadline, { day: 'numeric', month: 'short' })}{overdue && ' · overdue'}
          </div>

          {item.status === 'change_requested' && item.changeReason && (
            <div style={{ marginTop: 12, padding: '10px 12px', background: 'hsl(38 95% 97%)', border: '1px solid hsl(38 90% 86%)', borderRadius: 8 }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'hsl(28 90% 35%)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4 }}>WTS requested a change</div>
              <div style={{ fontSize: 13, color: 'hsl(0 0% 25%)', lineHeight: 1.5 }}>{item.changeReason}</div>
            </div>
          )}

          <div style={{ marginTop: 14 }}>
            {editable ? (
              <>
                <PortalInput item={item} value={draft} onChange={setDraft} />
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 12 }}>
                  <Button onClick={() => onSubmit(item, draft)} disabled={!hasValue(item.type, draft)}>
                    <Icon name="send" size={13} /> {item.status === 'change_requested' ? 'Re-submit' : 'Submit'}
                  </Button>
                  {item.required && !hasValue(item.type, draft) && <span style={{ fontSize: 12, color: 'var(--muted-foreground)' }}>Required before the engagement can close</span>}
                </div>
              </>
            ) : (
              <div style={{ padding: '12px 14px', background: 'hsl(220 14% 98%)', border: '1px solid var(--border)', borderRadius: 8 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--muted-foreground)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>
                  {item.status === 'submitted' ? 'Submitted — under review by WTS' : 'Accepted by WTS'}
                </div>
                <ItemValueView item={item} />
              </div>
            )}
          </div>

          <div style={{ marginTop: 10 }}>
            <button type="button" className="wts-link" style={{ fontSize: 12.5, color: 'hsl(213 80% 42%)' }} onClick={() => setShowComments(s => !s)}>
              <Icon name="message-circle" size={12} style={{ verticalAlign: '-2px', marginRight: 4 }} />
              {item.comments.length > 0 ? `${item.comments.length} comment${item.comments.length > 1 ? 's' : ''}` : 'Add a comment'}
            </button>
            {showComments && (
              <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 10 }}>
                {item.comments.map((c, i) => (
                  <div key={i} style={{ display: 'flex', gap: 9 }}>
                    <span style={{ width: 22, height: 22, borderRadius: '50%', flexShrink: 0, display: 'grid', placeItems: 'center', background: c.role === 'staff' ? 'hsl(213 70% 92%)' : 'hsl(28 80% 93%)', color: c.role === 'staff' ? 'hsl(213 70% 32%)' : 'hsl(28 80% 32%)' }}><Icon name={c.role === 'staff' ? 'briefcase' : 'user'} size={11} /></span>
                    <div><div style={{ fontSize: 12 }}><strong>{c.author}</strong> <span style={{ color: 'var(--muted-foreground)' }}>· {formatDate(c.at, { day: 'numeric', month: 'short' })}</span></div><div style={{ fontSize: 13, marginTop: 1 }}>{c.text}</div></div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Engagement view inside the portal ─────────────────────────────────────
const PortalEngagement = ({ eng, onBack }) => {
  const toast = useToast();
  const [over, setOver] = useStateP({});
  const items = useMemoP(() => getItemsForEngagement(eng.id).map(i => over[i.id] || i), [eng.id, over]);
  const st = useMemoP(() => {
    const req = items.filter(i => i.required);
    return { acceptedRequired: req.filter(i => i.status === 'accepted').length, requiredTotal: req.length };
  }, [items]);

  const submit = (item, value) => {
    const next = { ...item, status: 'submitted', value,
      versions: [...item.versions, { v: item.versions.length + 1, at: '2025-05-16', by: PORTAL_USER.name, note: '' }] };
    setOver(o => ({ ...o, [item.id]: next }));
    toast.success('Submitted to WTS', item.label);
  };

  const actionNeeded = items.filter(i => i.status === 'pending' || i.status === 'change_requested');
  const underReview  = items.filter(i => i.status === 'submitted');
  const accepted     = items.filter(i => i.status === 'accepted');

  const Section = ({ title, list, accent }) => list.length === 0 ? null : (
    <div style={{ marginTop: 26 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: accent || 'var(--foreground)' }}>{title}</span>
        <span className="ck-badge ck-badge--secondary">{list.length}</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {list.map(it => <PortalItemCard key={it.id} item={it} onSubmit={submit} />)}
      </div>
    </div>
  );

  return (
    <div style={{ maxWidth: 760, margin: '0 auto', padding: '28px 24px 64px' }}>
      <button type="button" className="wts-link" style={{ fontSize: 13, marginBottom: 14 }} onClick={onBack}>← All engagements</button>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 600, letterSpacing: '-0.02em', margin: 0 }}>{eng.name}</h1>
          <div style={{ fontSize: 13.5, color: 'var(--muted-foreground)', marginTop: 6 }}>{serviceLineLabel(eng.serviceLine)} · {eng.period} · WTS Cyprus</div>
        </div>
        <StatusBadge status={eng.status} />
      </div>
      <div style={{ marginTop: 18, padding: '14px 16px', border: '1px solid var(--border)', borderRadius: 10, background: 'var(--card)', boxShadow: 'var(--shadow-xs)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
          <span style={{ fontSize: 12.5, color: 'var(--muted-foreground)' }}>Your progress</span>
          <span style={{ fontSize: 12.5, fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>{st.acceptedRequired} of {st.requiredTotal} required items accepted</span>
        </div>
        <ProgressBar value={st.acceptedRequired} max={st.requiredTotal} color="hsl(213 80% 45%)" height={6} />
        {actionNeeded.length > 0 && <div style={{ fontSize: 12.5, color: 'hsl(28 90% 35%)', marginTop: 10, fontWeight: 500 }}><Icon name="alert-circle" size={12} style={{ verticalAlign: '-2px', marginRight: 4 }} />{actionNeeded.length} item{actionNeeded.length > 1 ? 's need' : ' needs'} your attention</div>}
      </div>

      <Section title="Action needed" list={actionNeeded} accent="hsl(28 90% 35%)" />
      <Section title="Under review by WTS" list={underReview} accent="hsl(213 80% 38%)" />
      <Section title="Accepted" list={accepted} accent="hsl(142 55% 30%)" />
    </div>
  );
};

// ── Portal home (engagement list) ─────────────────────────────────────────
const PortalHome = ({ engagements, onOpen }) => (
  <div style={{ maxWidth: 760, margin: '0 auto', padding: '32px 24px 64px' }}>
    <h1 style={{ fontSize: 24, fontWeight: 600, letterSpacing: '-0.02em', margin: 0 }}>Welcome, {PORTAL_USER.name.split(' ')[0]}</h1>
    <p style={{ fontSize: 14, color: 'var(--muted-foreground)', marginTop: 8, lineHeight: 1.55 }}>
      Here are the WTS engagements you’re attached to. Open one to upload documents and answer requests.
    </p>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 24 }}>
      {engagements.map(eng => {
        const items = getItemsForEngagement(eng.id);
        const req = items.filter(i => i.required);
        const acceptedRequired = req.filter(i => i.status === 'accepted').length;
        const needs = items.filter(i => i.status === 'pending' || i.status === 'change_requested').length;
        const team = eng.assigned.map(getUserById).filter(Boolean);
        return (
          <button key={eng.id} type="button" className="wts-portal-card" onClick={() => onOpen(eng.id)}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
              <div style={{ minWidth: 0, textAlign: 'left' }}>
                <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em' }}>{eng.name}</div>
                <div style={{ fontSize: 13, color: 'var(--muted-foreground)', marginTop: 3 }}>{serviceLineLabel(eng.serviceLine)} · {eng.period}</div>
              </div>
              <StatusBadge status={eng.status} />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 16 }}>
              <div style={{ flex: 1 }}><ProgressBar value={acceptedRequired} max={req.length} color="hsl(213 80% 45%)" /></div>
              <span style={{ fontSize: 12, color: 'var(--muted-foreground)', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{acceptedRequired}/{req.length} accepted</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 14 }}>
              {needs > 0
                ? <span style={{ fontSize: 12.5, color: 'hsl(28 90% 35%)', fontWeight: 500 }}><Icon name="alert-circle" size={12} style={{ verticalAlign: '-2px', marginRight: 4 }} />{needs} need{needs > 1 ? '' : 's'} your attention</span>
                : <span style={{ fontSize: 12.5, color: 'hsl(142 55% 32%)', fontWeight: 500 }}><Icon name="check-circle-2" size={12} style={{ verticalAlign: '-2px', marginRight: 4 }} />All done</span>}
              <span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--muted-foreground)' }}>WTS team <AvatarStack users={team} size={20} max={3} /></span>
            </div>
          </button>
        );
      })}
    </div>
  </div>
);

// ── Portal shell ──────────────────────────────────────────────────────────
const ClientPortal = ({ onExit }) => {
  const [engId, setEngId] = useStateP(null);
  const client = getClientById(PORTAL_USER.clientId);
  const myEngagements = useMemoP(() => ENGAGEMENTS
    .filter(e => e.clientId === PORTAL_USER.clientId && e.contactEmails.includes(PORTAL_USER.email))
    .sort((a, b) => (a.status === 'completed') - (b.status === 'completed')), []);
  const eng = engId ? getEngagementById(engId) : null;

  return (
    <div className="wts-portal">
      <header className="wts-portal__header">
        <div className="wts-portal__brand">
          <div className="wts-sidebar__logo" style={{ width: 28, height: 28 }}>W</div>
          <div style={{ lineHeight: 1.2 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600, letterSpacing: '-0.01em', whiteSpace: 'nowrap' }}>WTS Cyprus</div>
            <div style={{ fontSize: 11, color: 'var(--muted-foreground)', whiteSpace: 'nowrap' }}>Client Portal</div>
          </div>
        </div>
        <div style={{ flex: 1 }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 12.5, fontWeight: 500 }}>{PORTAL_USER.name}</div>
            <div style={{ fontSize: 11, color: 'var(--muted-foreground)' }}>{client.legalName}</div>
          </div>
          <Button variant="outline" size="sm" onClick={onExit}><Icon name="log-out" size={13} /> Exit to staff view</Button>
        </div>
      </header>
      <div className="wts-portal__body">
        {eng
          ? <PortalEngagement eng={eng} onBack={() => setEngId(null)} />
          : <PortalHome engagements={myEngagements} onOpen={setEngId} />}
      </div>
    </div>
  );
};

Object.assign(window, { ClientPortal });
