// Prodz — Collab flow. Tapping "Collab" on a profile or person card opens a
// chooser (brief: two distinct intents):
//   · Invita a un lavoro (Invite to job) — attach the job details, then send an
//     invitation tied to a Job Call conversation.
//   · Proposta di collaborazione (Collab proposal) — send a collaboration
//     request to the user plus a request to schedule a meeting.
function CollabFlow({ person, onClose, onSubmit }) {
  const { L } = useL();
  const { Button } = window.ProdzDesignSystem_d0b87b;
  const [mode, setMode] = useStateS('choose');          // choose | job | proposal
  const first = person && person.name ? person.name.split(' ')[0] : '';

  // job invite fields
  const [role, setRole] = useStateS('');
  const [dates, setDates] = useStateS('');
  const [paid, setPaid] = useStateS(true);
  const [jobNote, setJobNote] = useStateS('');

  // proposal fields
  const [proposalNote, setProposalNote] = useStateS('');
  const [meetWhen, setMeetWhen] = useStateS('');
  const meetOptions = [
    { it: 'Questa settimana', en: 'This week' },
    { it: 'Prossima settimana', en: 'Next week' },
    { it: 'Videocall', en: 'Video call' },
  ];

  const now = { it: 'adesso', en: 'now' };

  const sendJob = () => {
    const roleTxt = role.trim() || L('un ruolo nel team', 'a role on the team');
    onSubmit({
      id: 'conv-' + Date.now(), person: person.id, org: null,
      kind: 'job', subject: { it: 'Invito a un lavoro', en: 'Job invitation' }, unread: 0,
      time: now, preview: { it: 'Hai inviato un invito a un lavoro', en: 'You sent a job invitation' },
      messages: [{
        me: true, time: L('adesso', 'now'),
        text: { it: `Ciao ${first}! Vorrei invitarti per ${roleTxt}.`, en: `Hi ${first}! I'd like to invite you for ${roleTxt}.` },
        card: { type: 'job', role: role.trim(), dates: dates.trim(), paid, note: jobNote.trim() },
      }],
    }, L('Invito inviato · è nell’Inbox', 'Invitation sent · it’s in your Inbox'));
  };

  const sendProposal = () => {
    const msg = proposalNote.trim();
    const when = meetWhen || tr(L, meetOptions[0]);
    const messages = [{
      me: true, time: L('adesso', 'now'),
      text: msg
        ? { it: msg, en: msg }
        : { it: `Ciao ${first}! Ti va di collaborare a un progetto insieme?`, en: `Hi ${first}! Would you like to collaborate on a project together?` },
    }, {
      me: true, time: L('adesso', 'now'),
      text: { it: 'Ti va di fissare un incontro per parlarne?', en: 'Shall we set up a meeting to talk it through?' },
      card: { type: 'meeting', when },
    }];
    onSubmit({
      id: 'conv-' + Date.now(), person: person.id, org: null,
      kind: 'collab', subject: { it: 'Proposta di collaborazione', en: 'Collaboration proposal' }, unread: 0,
      time: now, preview: { it: 'Hai proposto una collaborazione e un incontro', en: 'You proposed a collaboration and a meeting' },
      messages,
    }, L('Proposta inviata · è nell’Inbox', 'Proposal sent · it’s in your Inbox'));
  };

  // ---- chooser ----
  if (mode === 'choose') {
    return (
      <div>
        <Eyebrow color="var(--prodz-teal)" style={{ marginBottom: 4 }}>{L('Collabora con', 'Collaborate with')}</Eyebrow>
        <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--text-primary)', marginBottom: 16 }}>{person ? person.name : ''}</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <OptionCard icon="Megaphone" tint="var(--prodz-gold)"
            title={L('Invita a un lavoro', 'Invite to a job')}
            sub={L('Allega i dettagli del lavoro e invia un invito.', 'Attach the job details and send an invitation.')}
            onClick={() => setMode('job')} />
          <OptionCard icon="Handshake" tint="var(--prodz-teal)"
            title={L('Proposta di collaborazione', 'Collab proposal')}
            sub={L('Invia una richiesta e proponi un incontro.', 'Send a request and propose a meeting.')}
            onClick={() => setMode('proposal')} />
        </div>
      </div>
    );
  }

  // ---- job invite form ----
  if (mode === 'job') {
    return (
      <div>
        <SheetHead icon="Megaphone" tint="var(--prodz-gold)" eyebrow={L('Invita a un lavoro', 'Invite to a job')} title={person ? person.name : ''} onBack={() => setMode('choose')} L={L} />
        <CField label={L('Ruolo cercato', 'Role wanted')}>
          <input value={role} onChange={(e) => setRole(e.target.value)} placeholder={L('es. Gaffer, 2nd AC…', 'e.g. Gaffer, 2nd AC…')} style={cInput} />
        </CField>
        <CField label={L('Date', 'Dates')}>
          <input value={dates} onChange={(e) => setDates(e.target.value)} placeholder={L('es. 24 – 26 Mag', 'e.g. May 24 – 26')} style={cInput} />
        </CField>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 14px', margin: '4px 0 0', background: 'var(--surface-raised)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--ring-inset-hairline)' }}>
          <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-body)' }}>{L('Retribuito', 'Paid')}</span>
          <button onClick={() => setPaid((v) => !v)} aria-label="Toggle paid" style={{ width: 46, height: 28, borderRadius: 14, border: 'none', cursor: 'pointer', padding: 3, background: paid ? 'var(--prodz-teal)' : 'var(--ink-700)', transition: 'background 160ms', display: 'flex', justifyContent: paid ? 'flex-end' : 'flex-start' }}>
            <span style={{ width: 22, height: 22, borderRadius: '50%', background: '#fff' }} />
          </button>
        </div>
        <CField label={L('Note', 'Notes')} style={{ marginTop: 12 }}>
          <textarea value={jobNote} onChange={(e) => setJobNote(e.target.value)} placeholder={L('Dettagli del lavoro, location, compenso…', 'Job details, location, rate…')} style={{ ...cInput, minHeight: 72, resize: 'none', padding: '11px 14px', lineHeight: 1.5 }} />
        </CField>
        <div style={{ marginTop: 16 }}>
          <Button variant="primary" glow fullWidth leadingIcon={<Ic n="Send" s={16} />} onClick={sendJob}>{L('Invia invito', 'Send invitation')}</Button>
        </div>
      </div>
    );
  }

  // ---- collab proposal ----
  return (
    <div>
      <SheetHead icon="Handshake" tint="var(--prodz-teal)" eyebrow={L('Proposta di collaborazione', 'Collab proposal')} title={person ? person.name : ''} onBack={() => setMode('choose')} L={L} />
      <CField label={L('Messaggio', 'Message')}>
        <textarea value={proposalNote} onChange={(e) => setProposalNote(e.target.value)} placeholder={L('Racconta la tua idea di collaborazione…', 'Describe your collaboration idea…')} style={{ ...cInput, minHeight: 84, resize: 'none', padding: '11px 14px', lineHeight: 1.5 }} />
      </CField>
      <CField label={L('Proponi un incontro', 'Propose a meeting')} style={{ marginTop: 12 }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {meetOptions.map((o) => {
            const v = tr(L, o);
            const on = meetWhen === v;
            return (
              <button key={v} onClick={() => setMeetWhen(on ? '' : v)} style={{
                height: 38, padding: '0 14px', borderRadius: 'var(--radius-pill)', border: 'none', cursor: 'pointer',
                fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap',
                background: on ? 'var(--teal-surface)' : 'var(--surface-raised)',
                color: on ? 'var(--prodz-teal)' : 'var(--text-muted)',
                boxShadow: on ? 'var(--ring-teal)' : 'var(--ring-inset-hairline)',
              }}>{v}</button>
            );
          })}
        </div>
      </CField>
      <div style={{ marginTop: 18 }}>
        <Button variant="primary" glow fullWidth leadingIcon={<Ic n="Send" s={16} />} onClick={sendProposal}>{L('Invia proposta', 'Send proposal')}</Button>
      </div>
    </div>
  );
}

function OptionCard({ icon, tint, title, sub, onClick }) {
  return (
    <button onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 13, width: '100%', padding: 14, border: 'none', cursor: 'pointer', textAlign: 'left', borderRadius: 'var(--radius-lg)', background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)' }}>
      <span style={{ width: 44, height: 44, borderRadius: 13, flexShrink: 0, background: 'var(--surface-card)', boxShadow: 'var(--ring-inset-hairline)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Ic n={icon} s={20} color={tint} />
      </span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: 'block', fontSize: 15, fontWeight: 700, color: 'var(--text-primary)' }}>{title}</span>
        <span style={{ display: 'block', fontSize: 12.5, color: 'var(--text-muted)', marginTop: 2, lineHeight: 1.4 }}>{sub}</span>
      </span>
      <Ic n="ChevronRight" s={18} color="var(--text-subtle)" />
    </button>
  );
}

function SheetHead({ icon, tint, eyebrow, title, onBack, L }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 16 }}>
      <button onClick={onBack} aria-label={L('Indietro', 'Back')} style={{ width: 34, height: 34, borderRadius: '50%', border: 'none', cursor: 'pointer', flexShrink: 0, background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Ic n="ChevronLeft" s={18} color="var(--text-muted)" />
      </button>
      <span style={{ width: 38, height: 38, borderRadius: 11, flexShrink: 0, background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Ic n={icon} s={18} color={tint} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <Eyebrow color={tint}>{eyebrow}</Eyebrow>
        <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text-primary)', marginTop: 1 }}>{title}</div>
      </div>
    </div>
  );
}

function CField({ label, children, style }) {
  return (
    <div style={{ ...style }}>
      <span style={{ display: 'block', fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-subtle)', margin: '0 0 7px' }}>{label}</span>
      {children}
    </div>
  );
}

const cInput = { width: '100%', height: 46, padding: '0 14px', borderRadius: 'var(--radius-md)', border: 'none', outline: 'none', background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)', color: 'var(--text-body)', fontSize: 15, fontFamily: 'var(--font-ui)' };

// Structured message attachment (job details / meeting request) for the Inbox.
function CollabCard({ card, L }) {
  if (!card) return null;
  if (card.type === 'job') {
    return (
      <div style={{ marginTop: 8, padding: 12, borderRadius: 14, background: 'rgba(212,175,55,0.12)', boxShadow: 'inset 0 0 0 1px rgba(212,175,55,0.35)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 8 }}>
          <Ic n="Megaphone" s={14} color="var(--prodz-gold)" />
          <span style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--prodz-gold)' }}>{L('Dettagli del lavoro', 'Job details')}</span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {card.role && <CardRow icon="Briefcase" text={card.role} />}
          {card.dates && <CardRow icon="Calendar" text={card.dates} />}
          <CardRow icon="BadgeEuro" text={card.paid ? L('Retribuito', 'Paid') : L('Non retribuito', 'Unpaid')} />
          {card.note && <CardRow icon="StickyNote" text={card.note} />}
        </div>
      </div>
    );
  }
  if (card.type === 'meeting') {
    return (
      <div style={{ marginTop: 8, padding: 12, borderRadius: 14, background: 'var(--teal-surface)', boxShadow: 'var(--ring-teal)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 8 }}>
          <Ic n="CalendarClock" s={14} color="var(--prodz-teal)" />
          <span style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--prodz-teal)' }}>{L('Richiesta di incontro', 'Meeting request')}</span>
        </div>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--text-primary)', marginBottom: 10 }}>{card.when}</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <span style={{ flex: 1, textAlign: 'center', height: 32, lineHeight: '32px', borderRadius: 'var(--radius-pill)', background: 'var(--prodz-teal)', color: 'var(--text-on-accent)', fontSize: 12.5, fontWeight: 700 }}>{L('Accetta', 'Accept')}</span>
          <span style={{ flex: 1, textAlign: 'center', height: 32, lineHeight: '32px', borderRadius: 'var(--radius-pill)', background: 'var(--surface-card)', color: 'var(--text-muted)', fontSize: 12.5, fontWeight: 700, boxShadow: 'var(--ring-inset-hairline)' }}>{L('Proponi altro', 'Suggest other')}</span>
        </div>
      </div>
    );
  }
  return null;
}

function CardRow({ icon, text }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <Ic n={icon} s={14} color="var(--text-muted)" />
      <span style={{ fontSize: 13, color: 'var(--text-body)' }}>{text}</span>
    </div>
  );
}

Object.assign(window, { CollabFlow, OptionCard, SheetHead, CField, CollabCard });
