// destiny.jsx — DestinyDrawer slide-in panel
// t and React hooks are available from components.jsx (loaded first)

function DestinyDrawer({ item, itemType = 'service', people, onSave, onClose }) {
  const [selectedDestiny, setSelectedDestiny] = useState(item?.destiny || null);
  const [selectedPeople, setSelectedPeople] = useState(item?.assignees || []);
  const [note, setNote] = useState(item?.note || '');

  // Reset when item changes
  useEffect(() => {
    setSelectedDestiny(item?.destiny || null);
    setSelectedPeople(item?.assignees || []);
    setNote(item?.note || '');
  }, [item?.id]);

  if (!item) return null;

  const destinyOptions = [
    {
      id: 'people',
      label: t.destiny.people,
      desc: t.destiny.people_desc,
      color: 'var(--destiny-people)',
      icon: 'people',
    },
    {
      id: 'oblio',
      label: t.destiny.oblio,
      desc: t.destiny.oblio_desc,
      color: 'var(--destiny-oblio)',
      icon: 'oblio',
    },
    {
      id: 'hidden',
      label: t.destiny.hidden,
      desc: t.destiny.hidden_desc,
      color: 'var(--destiny-hidden)',
      icon: 'eye_off',
    },
  ];

  function togglePerson(id) {
    setSelectedPeople(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  }

  function handleSave() {
    onSave({
      ...item,
      destiny: selectedDestiny,
      assignees: selectedDestiny === 'people' ? selectedPeople : [],
      note,
    });
    onClose();
  }

  return (
    <>
      <div className="backdrop" onClick={onClose} />
      <div className="drawer fade-in">
        {/* Header */}
        <div className="drawer-header">
          <div style={{ flex: 1 }}>
            <div className="t-eyebrow" style={{ marginBottom: 6 }}>
              {itemType === 'service' ? 'Servizio digitale' : itemType === 'asset' ? 'Asset reale' : 'Memoria'}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              {itemType === 'service' && item.icon && (
                <ServiceBadge icon={item.icon} color={item.color} size={40} />
              )}
              {itemType === 'asset' && (
                <div style={{ fontSize: 28 }}>{item.icon}</div>
              )}
              <div>
                <div style={{ fontSize: 17, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.2 }}>
                  {item.name || item.title}
                </div>
                {item.email && (
                  <div className="t-mono" style={{ marginTop: 2 }}>
                    {item.email}
                  </div>
                )}
                {item.category && (
                  <div style={{ marginTop: 4 }}>
                    <span className="chip chip-muted" style={{ fontSize: 11 }}>
                      {item.category}
                    </span>
                  </div>
                )}
              </div>
            </div>
          </div>
          <button
            className="btn btn-ghost btn-icon"
            onClick={onClose}
            style={{ flexShrink: 0 }}
          >
            <Icon name="close" size={18} />
          </button>
        </div>

        {/* Body */}
        <div className="drawer-body">
          {/* Destiny section title */}
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>
              {t.destiny.title}
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-muted)' }}>
              {t.destiny.sub}
            </div>
          </div>

          {/* Destiny options */}
          <div className="col" style={{ gap: 8, marginBottom: 24 }}>
            {destinyOptions.map(opt => (
              <div
                key={opt.id}
                className={`destiny-card${selectedDestiny === opt.id ? ' selected' : ''}`}
                onClick={() => setSelectedDestiny(opt.id)}
              >
                <div className="dot" style={{ background: opt.color }} />
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                    <Icon name={opt.icon} size={15} color={opt.color} />
                    <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>
                      {opt.label}
                    </span>
                    {selectedDestiny === opt.id && (
                      <span style={{ marginLeft: 'auto' }}>
                        <Icon name="check" size={15} color="var(--ink)" />
                      </span>
                    )}
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--ink-muted)' }}>
                    {opt.desc}
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* People picker — shown when "people" selected */}
          {selectedDestiny === 'people' && (
            <div style={{ marginBottom: 24 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)', marginBottom: 12 }}>
                {t.destiny.choose_people}
              </div>
              <div className="people-picker">
                {people.map(p => {
                  const sel = selectedPeople.includes(p.id);
                  return (
                    <div
                      key={p.id}
                      className={`people-picker-item${sel ? ' selected' : ''}`}
                      onClick={() => togglePerson(p.id)}
                    >
                      <Monogram initials={p.initials} color={p.color} size="sm" />
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>
                          {p.name}
                        </div>
                        <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>
                          {p.rel}
                        </div>
                      </div>
                      {sel && (
                        <div style={{
                          width: 20,
                          height: 20,
                          borderRadius: '50%',
                          background: 'var(--ink)',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                        }}>
                          <Icon name="check" size={11} color="#fff" strokeWidth={2.5} />
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
              {selectedPeople.length > 0 && (
                <div style={{ marginTop: 12, fontSize: 12, color: 'var(--ink-muted)', display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon name="clock" size={13} />
                  {t.destiny.only_see}
                </div>
              )}
            </div>
          )}

          {/* Note */}
          <div>
            <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)', marginBottom: 8 }}>
              Nota privata
            </div>
            <textarea
              className="input"
              style={{ minHeight: 88, resize: 'vertical', lineHeight: 1.5 }}
              placeholder="Aggiungi un contesto o delle istruzioni..."
              value={note}
              onChange={e => setNote(e.target.value)}
            />
          </div>
        </div>

        {/* Footer */}
        <div className="drawer-footer">
          <button className="btn btn-secondary" onClick={onClose}>
            {t.common.cancel}
          </button>
          <button
            className="btn btn-primary"
            onClick={handleSave}
            disabled={!selectedDestiny}
            style={{ opacity: selectedDestiny ? 1 : 0.45 }}
          >
            <Icon name="check" size={15} color="#fff" />
            {t.destiny.save}
          </button>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { DestinyDrawer });
