// care.jsx — Vet contacts + Symptoms log + Vet-visit prep (Claude-assisted)

// ─── Vet Contacts (global, used in Profile) ──────────────────────────────
const VET_TYPES = [
  { id: 'primary',   lbl: 'Primary vet',   glyph: '✚', tint: 'forest' },
  { id: 'emergency', lbl: 'Emergency vet', glyph: '!', tint: 'terra'  },
  { id: 'poison',    lbl: 'Poison control', glyph: '☣', tint: 'honey' },
  { id: 'microchip', lbl: 'Microchip lookup', glyph: '◉', tint: 'pond' },
  { id: 'other',     lbl: 'Other',         glyph: '◧', tint: 'sand'  },
];
const vetTypeOf = (id) => VET_TYPES.find((t) => t.id === id) || VET_TYPES[4];

function VetContacts({ contacts, onAdd, onRemove }) {
  const [adding, setAdding] = React.useState(false);
  const [type, setType] = React.useState('primary');
  const [name, setName] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [address, setAddress] = React.useState('');
  const [note, setNote] = React.useState('');

  const reset = () => { setType('primary'); setName(''); setPhone(''); setAddress(''); setNote(''); };
  const save = () => {
    if (!name.trim()) return;
    onAdd && onAdd({ id: `v-${Date.now()}`, type, name: name.trim(),
                     phone: phone.trim(), address: address.trim(), note: note.trim() });
    reset(); setAdding(false);
  };

  return (
    <>
      <window.SectionHeader kicker="Care team" title="Vet" accent="contacts" count={`${(contacts || []).length}`} />
      <div className="health-card vets-card">
        {(contacts || []).length === 0 && !adding && (
          <div className="health-empty">
            <div className="health-empty-mark">✚</div>
            <div className="health-empty-t">No contacts saved.</div>
            <div className="health-empty-s">
              Primary vet, emergency clinic, poison control — keep them one tap away
              for the panicked nights.
            </div>
          </div>
        )}

        {(contacts || []).map((c) => {
          const t = vetTypeOf(c.type);
          return (
            <div key={c.id} className="vet-row">
              <div className="vet-icon" data-type={c.type}>
                <span>{t.glyph}</span>
              </div>
              <div className="vet-body">
                <div className="vet-name">{c.name}</div>
                <div className="vet-type-pill">{t.lbl}</div>
                {c.phone && (
                  <a className="vet-phone" href={`tel:${c.phone}`} onClick={(e) => e.stopPropagation()}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                         strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/>
                    </svg>
                    {c.phone}
                  </a>
                )}
                {c.address && <div className="vet-address">{c.address}</div>}
                {c.note && <div className="vet-note">{c.note}</div>}
              </div>
              <button className="r-del" onClick={() => onRemove && onRemove(c.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">
              <div className="doc-type-tabs">
                {VET_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.split(' ')[0]}</span>
                  </button>
                ))}
              </div>
            </div>
            <div className="health-form-row">
              <input className="health-input" autoFocus value={name}
                     onChange={(e) => setName(e.target.value)}
                     placeholder="Name (e.g. Dr. Park, Maple Vet Clinic)" />
            </div>
            <div className="health-form-row split">
              <input className="health-input" value={phone}
                     onChange={(e) => setPhone(e.target.value)}
                     placeholder="Phone (e.g. +1 555 0103)" />
            </div>
            <div className="health-form-row">
              <input className="health-input" value={address}
                     onChange={(e) => setAddress(e.target.value)}
                     placeholder="Address (optional)" />
            </div>
            <div className="health-form-row">
              <input className="health-input" value={note}
                     onChange={(e) => setNote(e.target.value)}
                     placeholder="Notes — hours, parking, who to ask for…" />
            </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 }}>Save contact</button>
            </div>
          </div>
        ) : (
          <button className="r-add" onClick={() => setAdding(true)}>
            <span className="r-plus">+</span>
            <span>Add a vet or emergency contact</span>
          </button>
        )}
      </div>
    </>
  );
}

// ─── Symptoms log + vet-visit summary ────────────────────────────────────
const SEVERITY = [
  { id: 'mild',     lbl: 'Mild',     dots: 1 },
  { id: 'moderate', lbl: 'Moderate', dots: 2 },
  { id: 'urgent',   lbl: 'Urgent',   dots: 3 },
];

function SymptomsLog({ folk, entries, onAdd, onRemove, onAsk }) {
  const [adding, setAdding] = React.useState(false);
  const [symptom, setSymptom] = React.useState('');
  const [severity, setSeverity] = React.useState('mild');
  const [note, setNote] = React.useState('');

  const list = (entries || []).slice().sort((a, b) => new Date(b.date) - new Date(a.date));

  const reset = () => { setSymptom(''); setSeverity('mild'); setNote(''); };
  const save = () => {
    if (!symptom.trim()) return;
    onAdd && onAdd({
      id: `s-${Date.now()}`,
      date: window.TOOLS_NOW.toISOString(),
      symptom: symptom.trim(),
      severity, note: note.trim(),
    });
    reset(); setAdding(false);
  };

  const summary = () => {
    if (!onAsk || !list.length) return;
    const lines = list.slice(0, 10).reverse().map((e) => {
      const d = new Date(e.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
      return `• ${d} (${e.severity}): ${e.symptom}${e.note ? ' — ' + e.note : ''}`;
    }).join('\n');
    const pre = `You are helping me prepare for a vet visit for ${folk.name}, a ${folk.species}. ` +
                `Here is the symptom log:\n${lines}\n\nGive me a tidy summary I can show the vet: timeline, ` +
                `severity trend, any patterns, plus the top 3 questions I should ask. Keep it under 120 words.`;
    onAsk(folk, pre);
  };

  return (
    <>
      <window.SectionHeader kicker="Health" title="Symptoms" accent="& concerns" count={`${list.length}`} />
      <div className="health-card symptoms-card">
        {list.length === 0 && !adding && (
          <div className="health-empty">
            <div className="health-empty-mark">◑</div>
            <div className="health-empty-t">Nothing logged.</div>
            <div className="health-empty-s">
              Note anything that seems off — eating less, lump, lethargy.
              Tendlet can prepare a tidy vet-visit summary from your notes.
            </div>
          </div>
        )}

        {list.map((e) => {
          const sev = SEVERITY.find((s) => s.id === e.severity) || SEVERITY[0];
          return (
            <div key={e.id} className="symp-row">
              <div className={`symp-sev sev-${e.severity}`}>
                {Array.from({ length: 3 }).map((_, i) => (
                  <span key={i} className={i < sev.dots ? 'on' : ''}></span>
                ))}
              </div>
              <div className="symp-body">
                <div className="symp-name">{e.symptom}</div>
                <div className="symp-meta">
                  <span className="symp-date h-mono">
                    {new Date(e.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                  </span>
                  <span className="symp-sev-pill">{sev.lbl}</span>
                </div>
                {e.note && <div className="symp-note">"{e.note}"</div>}
              </div>
              <button className="r-del" onClick={() => onRemove && onRemove(e.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>
          );
        })}

        {list.length > 0 && (
          <button className="symp-summary" onClick={summary}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                 strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 3l1.8 4.5L18 9l-4.2 1.5L12 15l-1.8-4.5L6 9l4.2-1.5z"/>
              <circle cx="18" cy="18" r="1.2" fill="currentColor"/>
              <circle cx="5" cy="17" r="0.9" fill="currentColor"/>
            </svg>
            <span><b>Prepare a vet-visit summary</b> · uses your log</span>
          </button>
        )}

        {adding ? (
          <div className="health-form">
            <div className="health-form-row">
              <input className="health-input" autoFocus value={symptom}
                     onChange={(e) => setSymptom(e.target.value)}
                     placeholder="What's off? (e.g. eating less, lump on shoulder)" />
            </div>
            <div className="health-form-row">
              <div className="doc-type-tabs">
                {SEVERITY.map((s) => (
                  <button key={s.id} type="button"
                          className={severity === s.id ? 'on' : ''}
                          onClick={() => setSeverity(s.id)}>
                    <span className="dt-g">{Array.from({ length: s.dots }).map((_, i) =>
                      <span key={i} style={{ display: 'inline-block', width: 6, height: 6, borderRadius: 99, background: 'currentColor', marginRight: 2 }}></span>)}</span>
                    <span>{s.lbl}</span>
                  </button>
                ))}
              </div>
            </div>
            <div className="health-form-row">
              <input className="health-input" value={note}
                     onChange={(e) => setNote(e.target.value)}
                     placeholder="More detail — when, how often, what changed" />
            </div>
            <div className="r-add-actions">
              <button className="r-cancel" onClick={() => { reset(); setAdding(false); }}>Cancel</button>
              <button className="r-save" onClick={save} disabled={!symptom.trim()}
                      style={{ opacity: symptom.trim() ? 1 : 0.4 }}>Log symptom</button>
            </div>
          </div>
        ) : (
          <button className="r-add" onClick={() => setAdding(true)}>
            <span className="r-plus">+</span>
            <span>Log a symptom or concern for {folk.name}</span>
          </button>
        )}
      </div>
    </>
  );
}

Object.assign(window, { VetContacts, SymptomsLog, VET_TYPES });
