/* global React */
const { useState } = React;

// ---------- Icons ----------
const Icon = ({ name, size = 16, stroke = 1.6, ...rest }) => {
  const common = {
    width: size, height: size, viewBox: '0 0 24 24',
    fill: 'none', stroke: 'currentColor',
    strokeWidth: stroke, strokeLinecap: 'round', strokeLinejoin: 'round',
    ...rest,
  };
  switch (name) {
    case 'tree':
      return (
        <svg {...common}>
          <path d="M12 22V14"/>
          <path d="M5 14h14"/>
          <path d="M5 14V9"/>
          <path d="M19 14V9"/>
          <path d="M12 9V4"/>
          <circle cx="12" cy="3.2" r="1.4"/>
          <circle cx="5"  cy="8.2" r="1.4"/>
          <circle cx="19" cy="8.2" r="1.4"/>
        </svg>
      );
    case 'search':
      return (
        <svg {...common}>
          <circle cx="11" cy="11" r="7"/>
          <path d="M20 20l-3.5-3.5"/>
        </svg>
      );
    case 'plus':
      return (
        <svg {...common}>
          <path d="M12 5v14M5 12h14"/>
        </svg>
      );
    case 'minus':
      return (
        <svg {...common}>
          <path d="M5 12h14"/>
        </svg>
      );
    case 'close':
      return (
        <svg {...common}>
          <path d="M6 6l12 12M18 6L6 18"/>
        </svg>
      );
    case 'edit':
      return (
        <svg {...common}>
          <path d="M4 20h4l10-10-4-4L4 16v4z"/>
          <path d="M14 6l4 4"/>
        </svg>
      );
    case 'trash':
      return (
        <svg {...common}>
          <path d="M4 7h16"/>
          <path d="M10 11v6M14 11v6"/>
          <path d="M6 7l1 13a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-13"/>
          <path d="M9 7V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"/>
        </svg>
      );
    case 'more':
      return (
        <svg {...common}>
          <circle cx="5" cy="12" r="1.2"/>
          <circle cx="12" cy="12" r="1.2"/>
          <circle cx="19" cy="12" r="1.2"/>
        </svg>
      );
    case 'settings':
      return (
        <svg {...common}>
          <circle cx="12" cy="12" r="3"/>
          <path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9c.2.6.7 1 1.5 1h.1a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>
        </svg>
      );
    case 'sliders':
      return (
        <svg {...common}>
          <path d="M4 6h10M18 6h2"/>
          <circle cx="16" cy="6" r="2"/>
          <path d="M4 12h4M12 12h8"/>
          <circle cx="10" cy="12" r="2"/>
          <path d="M4 18h10M18 18h2"/>
          <circle cx="16" cy="18" r="2"/>
        </svg>
      );
    case 'logout':
      return (
        <svg {...common}>
          <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
          <path d="M16 17l5-5-5-5"/>
          <path d="M21 12H9"/>
        </svg>
      );
    case 'camera':
      return (
        <svg {...common}>
          <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2v11z"/>
          <circle cx="12" cy="13" r="4"/>
        </svg>
      );
    case 'home':
      return (
        <svg {...common}>
          <path d="M3 11l9-7 9 7v9a2 2 0 0 1-2 2h-4v-7h-6v7H5a2 2 0 0 1-2-2v-9z"/>
        </svg>
      );
    case 'check':
      return (
        <svg {...common}>
          <path d="M5 12l5 5L20 7"/>
        </svg>
      );
    default: return null;
  }
};

// ---------- Avatar ----------
function Avatar({ person, size }) {
  const { avatarColor, initials } = window.FamilyData;
  const style = { background: person.color || avatarColor(person.name || '?') };
  if (size) {
    style.width = size + 'px';
    style.height = size + 'px';
    style.fontSize = Math.round(size * 0.34) + 'px';
  }
  return (
    <div className={`avatar${person.deathDate ? ' deceased' : ''}`} style={style}>
      {person.photo
        ? <img src={person.photo} alt="" />
        : <span>{initials(person.name)}</span>}
    </div>
  );
}

// ---------- PersonCard ----------
function PersonCard({ person, pos, cardW, cardH, density, showNicknames, showDates, photoForward, focused, onClick }) {
  const { birthDate, deathDate } = person;
  const dates = (() => {
    if (birthDate || deathDate) {
      const b = birthDate ? birthDate.toString().slice(0, 4) : '';
      const d = deathDate ? deathDate.toString().slice(0, 4) : '';
      if (b && d) return `${b} – ${d}`;
      if (b && !deathDate) return `b. ${b}`;
      if (!b && d) return `d. ${d}`;
      if (b) return b;
    }
    return '';
  })();
  const classes = ['card'];
  if (density === 'compact') classes.push('compact');
  if (density === 'cozy') classes.push('cozy');
  if (photoForward) classes.push('photo-forward');
  if (deathDate) classes.push('deceased');
  if (focused) classes.push('focused');

  const style = {
    transform: `translate(${pos.x}px, ${pos.y}px)`,
    '--card-w': cardW + 'px',
    '--card-h': cardH + 'px',
  };

  const body = (
    <>
      <Avatar person={person} />
      <div className={photoForward ? 'card-body' : ''}>
        <p className="card-name">{person.name || 'Unnamed'}</p>
        {showNicknames && person.nickname && (
          <p className="card-nick">“{person.nickname}”</p>
        )}
        {showDates && dates && <p className="card-dates">{dates}</p>}
      </div>
    </>
  );

  return (
    <div
      className={classes.join(' ')}
      style={style}
      onClick={(e) => { e.stopPropagation(); onClick && onClick(person); }}
      data-person-id={person.id}
    >
      {body}
    </div>
  );
}

// ---------- Empty state ----------
function EmptyState({ onAdd }) {
  return (
    <div className="empty-state">
      <div className="empty-state-inner">
        <Icon name="tree" size={36} stroke={1.2} style={{ color: 'var(--accent)' }} />
        <h2>Your tree is empty</h2>
        <p>Start by adding yourself or an ancestor. From there, you can build outward — adding parents, siblings, partners, and children.</p>
        <button className="btn btn-primary" onClick={onAdd}>
          <Icon name="plus" size={14}/> Add the first person
        </button>
      </div>
    </div>
  );
}

// ---------- Menu (anchored popover) ----------
function Menu({ anchor, onClose, children }) {
  if (!anchor) return null;
  React.useEffect(() => {
    const onDoc = (e) => {
      if (!e.target.closest('.menu') && !e.target.closest('[data-menu-anchor]')) onClose();
    };
    setTimeout(() => document.addEventListener('mousedown', onDoc), 0);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [onClose]);
  return (
    <div className="menu" style={{ top: anchor.y, left: anchor.x }}>{children}</div>
  );
}

// Expose
Object.assign(window, { Icon, Avatar, PersonCard, EmptyState, Menu });
