// DetailSheet.jsx — right-side panel showing one object's details and log form

function DetailSheet({ obj, log, onClose, onLog, onUnlog }) {
  const [sketching, setSketching] = React.useState(false);
  const [noteDraft, setNoteDraft] = React.useState(log?.note || '');
  const [dateDraft, setDateDraft] = React.useState(
    log?.date || new Date().toISOString().slice(0, 10)
  );
  const [conditions, setConditions] = React.useState(log?.conditions || '');

  React.useEffect(() => {
    setNoteDraft(log?.note || '');
    setDateDraft(log?.date || new Date().toISOString().slice(0, 10));
    setConditions(log?.conditions || '');
  }, [obj?.id]);

  if (!obj) return null;

  const save = () => {
    onLog({ date: dateDraft, note: noteDraft, conditions });
  };

  return (
    <div className="sheet-overlay" onClick={onClose}>
      <div className="sheet" onClick={e => e.stopPropagation()}>
        <button className="sheet__close" onClick={onClose} aria-label="Close">
          <svg width="16" height="16" viewBox="0 0 16 16"><path d="M3 3 L13 13 M13 3 L3 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
        </button>

        <div className="sheet__hero" data-has-img={!!obj.img}>
          {obj.img ? (
            <>
              <img
                className="sheet__hero-img"
                src={obj.img}
                alt={obj.name}
                loading="lazy"
                onError={(e) => { e.currentTarget.style.display = 'none'; e.currentTarget.parentElement.dataset.hasImg = 'false'; }}
              />
              {obj.credit && (
                <div className="sheet__hero-credit mono">
                  {obj.source ? (
                    <a href={obj.source} target="_blank" rel="noopener noreferrer" title="View source & licence on Wikimedia Commons">
                      {obj.credit}
                      <svg width="9" height="9" viewBox="0 0 9 9" style={{marginLeft:4,verticalAlign:'baseline'}} aria-hidden="true"><path d="M3 1h5v5M8 1L3.5 5.5M1 3v5h5" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    </a>
                  ) : obj.credit}
                </div>
              )}
              {log && (
                <div className="sheet__hero-stamp mono">
                  <svg width="10" height="10" viewBox="0 0 10 10"><path d="M1.5 5.2l2.2 2.2L8.5 2.5" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  SEEN
                </div>
              )}
            </>
          ) : (
            <SkyGlyph cat={obj.cat} seen={!!log} size={120} />
          )}
        </div>

        <div className="sheet__kicker mono">{obj.cat.toUpperCase()} · ENTRY #{String(obj.id).toUpperCase()}</div>
        <h1 className="sheet__title">{obj.name}</h1>

        <div className="sheet__facts">
          <div className="fact">
            <div className="fact__label mono">MAGNITUDE</div>
            <div className="fact__value">{obj.mag != null ? `${obj.mag > 0 ? '+' : ''}${obj.mag}` : '—'}</div>
          </div>
          <div className="fact">
            <div className="fact__label mono">DIFFICULTY</div>
            <div className="fact__value" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <DifficultyDots level={obj.difficulty} />
              <span style={{ fontSize: 13, color: 'var(--ink-300)' }}>{['Easy', 'Easy', 'Medium', 'Hard', 'Expert'][obj.difficulty - 1]}</span>
            </div>
          </div>
          <div className="fact">
            <div className="fact__label mono">RA · DEC</div>
            <div className="fact__value mono" style={{ fontSize: 13 }}>{obj.ra} &nbsp; {obj.dec}</div>
          </div>
          <div className="fact">
            <div className="fact__label mono">BEST TIME</div>
            <div className="fact__value" style={{ fontSize: 13 }}>{obj.best}</div>
          </div>
        </div>

        <p className="sheet__blurb">{obj.blurb}</p>

        <div className="sheet__tip">
          <div className="sheet__tip-label mono">HOW TO FIND IT</div>
          <div>{obj.tip}</div>
        </div>

        <div className="sheet__tags">
          {obj.tags.map(t => <span key={t} className="tag mono">{t}</span>)}
        </div>

        <div className="sheet__log">
          <div className="sheet__log-header">
            <div className="sheet__log-title">
              {log ? 'Logged sighting' : 'Log a sighting'}
            </div>
            {log && (
              <button className="linkbtn" onClick={onUnlog}>remove</button>
            )}
          </div>

          <label className="field">
            <span className="field__label mono">DATE SEEN</span>
            <input
              type="date"
              value={dateDraft}
              onChange={e => setDateDraft(e.target.value)}
            />
          </label>

          <label className="field">
            <span className="field__label mono">SKY CONDITIONS</span>
            <div className="chips">
              {['Clear', 'Hazy', 'Partly cloudy', 'City lights', 'Dark sky'].map(c => (
                <button
                  type="button"
                  key={c}
                  className="chip"
                  data-active={conditions === c}
                  onClick={() => setConditions(c)}
                >{c}</button>
              ))}
            </div>
          </label>

          <label className="field">
            <span className="field__label mono">NOTES</span>
            <textarea
              rows={3}
              value={noteDraft}
              onChange={e => setNoteDraft(e.target.value)}
              placeholder="What did it look like? Who were you with?"
            />
          </label>

          <button className="btn-primary" onClick={save}>
            {log ? 'Update entry' : 'Mark as seen'}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DetailSheet });
