// health.jsx — Medications + Documents per folk

const DOC_TYPES = [
  { id: 'vet',       lbl: 'Vet',        glyph: '✚' },
  { id: 'insurance', lbl: 'Insurance',  glyph: '☂' },
  { id: 'legal',     lbl: 'Legal',      glyph: '§' },
  { id: 'id',        lbl: 'ID',         glyph: '◉' },
  { id: 'other',     lbl: 'Other',      glyph: '◧' },
];
const docTypeOf = (id) => DOC_TYPES.find((t) => t.id === id) || DOC_TYPES[4];

function fmtDocDate(iso) {
  if (!iso) return '—';
  try {
    const d = new Date(iso);
    return d.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  } catch (e) { return iso; }
}

// ─── Medications panel ───────────────────────────────────────────────────
function Medications({ folk, meds, onAdd, onRemove }) {
  const [adding, setAdding] = React.useState(false);
  const [name, setName] = React.useState('');
  const [dose, setDose] = React.useState('');
  const [freq, setFreq] = React.useState('daily');
  const [start, setStart] = React.useState('');
  const [end, setEnd] = React.useState('');
  const [note, setNote] = React.useState('');

  const reset = () => {
    setName(''); setDose(''); setFreq('daily'); setStart(''); setEnd(''); setNote('');
  };
  const save = () => {
    if (!name.trim()) return;
    onAdd && onAdd({
      name: name.trim(), dose: dose.trim(), freq, note: note.trim(),
      start: start || window.TOOLS_NOW.toISOString(), end: end || null,
    });
    reset();
    setAdding(false);
  };

  return (
    <>
      <window.SectionHeader kicker="Medications" title="Active" accent="meds" count={`${(meds || []).length}`} />
      <div className="health-card meds-card">
        {(meds || []).length === 0 && !adding && (
          <div className="health-empty">
            <div className="health-empty-mark">✚</div>
            <div className="health-empty-t">No active medications.</div>
            <div className="health-empty-s">
              Add prescriptions, supplements, or treatments so reminders show up alongside daily care.
            </div>
          </div>
        )}

        {(meds || []).map((m) => (
          <div key={m.id} className="med-row">
            <div className="med-pill" data-status={m.end ? 'ending' : 'active'}>
              <span className="med-dot"></span>
              <span>{m.end ? 'COURSE' : 'ACTIVE'}</span>
            </div>
            <div className="med-body">
              <div className="med-name">{m.name}</div>
              <div className="med-meta">
                {m.dose && <span><b>{m.dose}</b></span>}
                {m.dose && m.freq && <span className="dot">·</span>}
                {m.freq && <span>{m.freq}</span>}
              </div>
              <div className="med-when">
                <span>Started {fmtDocDate(m.start)}</span>
                {m.end && <span> · ends {fmtDocDate(m.end)}</span>}
              </div>
              {m.note && <div className="med-note">"{m.note}"</div>}
            </div>
            <button className="r-del" onClick={() => onRemove && onRemove(m.id)} aria-label="Remove">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                   strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
            </button>
          </div>
        ))}

        {adding ? (
          <div className="health-form">
            <div className="health-form-row">
              <input className="health-input" autoFocus value={name} onChange={(e) => setName(e.target.value)}
                     placeholder="Medication name (e.g. Metacam)" />
            </div>
            <div className="health-form-row split">
              <input className="health-input" value={dose} onChange={(e) => setDose(e.target.value)}
                     placeholder="Dose (e.g. 0.3 ml)" />
              <select className="health-input" value={freq} onChange={(e) => setFreq(e.target.value)}>
                <option value="daily">Once daily</option>
                <option value="twice daily">Twice daily</option>
                <option value="every other day">Every other day</option>
                <option value="weekly">Weekly</option>
                <option value="as needed">As needed</option>
              </select>
            </div>
            <div className="health-form-row split">
              <label className="health-mini">
                <span>Start</span>
                <input className="health-input" type="date" value={start} onChange={(e) => setStart(e.target.value)} />
              </label>
              <label className="health-mini">
                <span>End (optional)</span>
                <input className="health-input" type="date" value={end} onChange={(e) => setEnd(e.target.value)} />
              </label>
            </div>
            <div className="health-form-row">
              <input className="health-input" value={note} onChange={(e) => setNote(e.target.value)}
                     placeholder="Notes — vet, side effects, what it treats" />
            </div>
            <div className="r-add-actions">
              <button className="r-cancel" onClick={() => { reset(); setAdding(false); }}>Cancel</button>
              <button className="r-save" onClick={save} disabled={!name.trim()}
                      style={{ opacity: name.trim() ? 1 : 0.4 }}>
                Add medication
              </button>
            </div>
          </div>
        ) : (
          <button className="r-add" onClick={() => setAdding(true)}>
            <span className="r-plus">+</span>
            <span>Add a medication for {folk.name}</span>
          </button>
        )}
      </div>
    </>
  );
}

// ─── Documents panel ─────────────────────────────────────────────────────
function Documents({ folk, docs, onAdd, onRemove }) {
  const [adding, setAdding] = React.useState(false);
  const [title, setTitle] = React.useState('');
  const [type, setType] = React.useState('vet');
  const [date, setDate] = React.useState('');
  const [note, setNote] = React.useState('');
  const [fileName, setFileName] = React.useState('');
  const [fileUrl, setFileUrl] = React.useState('');
  const fileRef = React.useRef(null);

  const onPickFile = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => { setFileName(file.name); setFileUrl(ev.target.result); };
    reader.readAsDataURL(file);
  };

  const reset = () => {
    setTitle(''); setType('vet'); setDate(''); setNote(''); setFileName(''); setFileUrl('');
  };
  const save = () => {
    if (!title.trim()) return;
    onAdd && onAdd({
      title: title.trim(), type, date: date || window.TOOLS_NOW.toISOString(),
      note: note.trim(), fileName, fileUrl,
    });
    reset();
    setAdding(false);
  };

  return (
    <>
      <window.SectionHeader kicker="Documents" title="Records" accent="& papers" count={`${(docs || []).length}`} />
      <div className="health-card docs-card">
        {(docs || []).length === 0 && !adding && (
          <div className="health-empty">
            <div className="health-empty-mark">◧</div>
            <div className="health-empty-t">No documents yet.</div>
            <div className="health-empty-s">
              Vet records, vaccination certificates, microchip IDs, insurance papers — all in one place.
            </div>
          </div>
        )}

        {(docs || []).map((d) => {
          const t = docTypeOf(d.type);
          return (
            <div key={d.id} className="doc-row">
              <div className="doc-icon" data-type={d.type}>
                <span className="doc-glyph">{t.glyph}</span>
                {d.fileUrl && d.fileUrl.startsWith('data:image/') && (
                  <img className="doc-thumb" src={d.fileUrl} alt="" />
                )}
              </div>
              <div className="doc-body">
                <div className="doc-title">{d.title}</div>
                <div className="doc-meta">
                  <span className="doc-type-pill">{t.lbl}</span>
                  <span>{fmtDocDate(d.date)}</span>
                  {d.fileName && <span className="doc-file"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 3v6h6M14 3l6 6M6 3h8l6 6v12H6z"/></svg> {d.fileName}</span>}
                </div>
                {d.note && <div className="doc-note">{d.note}</div>}
              </div>
              <button className="r-del" onClick={() => onRemove && onRemove(d.id)} aria-label="Remove">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
              </button>
            </div>
          );
        })}

        {adding ? (
          <div className="health-form">
            <div className="health-form-row">
              <input className="health-input" autoFocus value={title} onChange={(e) => setTitle(e.target.value)}
                     placeholder="e.g. Rabies certificate, Microchip ID, Insurance policy" />
            </div>
            <div className="health-form-row">
              <div className="doc-type-tabs">
                {DOC_TYPES.map((opt) => (
                  <button key={opt.id} type="button"
                          className={type === opt.id ? 'on' : ''}
                          onClick={() => setType(opt.id)}>
                    <span className="dt-g">{opt.glyph}</span>
                    <span>{opt.lbl}</span>
                  </button>
                ))}
              </div>
            </div>
            <div className="health-form-row split">
              <label className="health-mini">
                <span>Date</span>
                <input className="health-input" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
              </label>
              <button type="button" className="health-file-btn" onClick={() => fileRef.current?.click()}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M14 3v6h6M14 3l6 6M6 3h8l6 6v12H6z"/>
                </svg>
                <span>{fileName || 'Attach file (optional)'}</span>
              </button>
              <input ref={fileRef} type="file" style={{ display: 'none' }}
                     accept="image/*,application/pdf" onChange={onPickFile} />
            </div>
            <div className="health-form-row">
              <input className="health-input" value={note} onChange={(e) => setNote(e.target.value)}
                     placeholder="Notes — clinic, expiry, reference number…" />
            </div>
            <div className="r-add-actions">
              <button className="r-cancel" onClick={() => { reset(); setAdding(false); }}>Cancel</button>
              <button className="r-save" onClick={save} disabled={!title.trim()}
                      style={{ opacity: title.trim() ? 1 : 0.4 }}>
                Add document
              </button>
            </div>
          </div>
        ) : (
          <button className="r-add" onClick={() => setAdding(true)}>
            <span className="r-plus">+</span>
            <span>Add a document for {folk.name}</span>
          </button>
        )}
      </div>
    </>
  );
}

Object.assign(window, { Medications, Documents, DOC_TYPES });
