/* Renders the populated plan as a print-ready document */

const { useMemo } = React;

function Val({ v, placeholder = '—' }) {
  if (!v || (typeof v === 'string' && !v.trim())) {
    return <span style={{ color: '#bbb' }}>{placeholder}</span>;
  }
  return <span>{v}</span>;
}

function Row({ k, v }) {
  return (
    <div className="doc-row">
      <div className="key">{k}</div>
      <div className="val"><Val v={v} /></div>
    </div>
  );
}

function Chips({ options, selected }) {
  const sel = selected || {};
  return (
    <div className="doc-checks">
      {options.map(o => (
        <span key={o} className={`doc-chip ${sel[o] ? 'on' : 'off'}`}>
          {sel[o] ? '●' : '○'} {o}
        </span>
      ))}
    </div>
  );
}

function ChipsSelectedOnly({ options, selected }) {
  const sel = selected || {};
  const on = options.filter(o => sel[o]);
  if (!on.length) return <span style={{ color: '#bbb', fontSize: '9.5pt' }}>None selected</span>;
  return (
    <div className="doc-checks">
      {on.map(o => (
        <span key={o} className="doc-chip on">✓ {o}</span>
      ))}
    </div>
  );
}

function DocSection({ num, title, children }) {
  return (
    <section className="doc-section">
      <h2>
        <span>{title}</span>
        <span className="sec-num">Section {num}</span>
      </h2>
      {children}
    </section>
  );
}

function PrintableDocument({ data }) {
  const d = data || {};
  const today = new Date().toLocaleDateString('en-US', {
    month: 'long', day: 'numeric', year: 'numeric'
  });

  return (
    <div className="doc" id="printable-doc">
      {/* Header */}
      <div className="doc-header">
        <div>
          <img src="medical-star.png" alt="Star of life symbol" className="staroflife" />
          <h1>Emergency Safety Plan</h1>
          <div className="doc-subtitle">For a child with disabilities during ICE encounters</div>
        </div>
        <div className="doc-header-r">
          Printed {today}<br/>
          Plan for: <strong>{d.child_name || '—'}</strong><br/>
          Keep this document with the child at all times.
        </div>
      </div>

      <div className="doc-alert">
        <strong>SHOW THIS PLAN TO ANY OFFICER IMMEDIATELY.</strong> This child has a disability and
        requires accommodations under the Americans with Disabilities Act (ADA) and Section 504, Rehabilitation Act of 1973.
        Non-compliance is not defiance — it is disability.
      </div>

      {/* 1. Identifying */}
      <DocSection num="01" title="Child's identifying information">
        <div className="doc-two-col">
          <div>
            <Row k="Full name" v={d.child_name} />
            <Row k="Nickname(s)" v={d.child_nickname} />
            <Row k="Date of birth" v={d.child_dob} />
            <Row k="Age" v={d.child_age} />
          </div>
          <div>
            <Row k="Primary language" v={d.child_language} />
            <Row k="Photo attached" v={d.photo_attached ? 'Yes — recent photo attached' : ''} />
            <Row k="Immigration attorney" v={d.attorney} />
          </div>
        </div>
        <div style={{marginTop: 8}}>
          <Row k="Physical description" v={d.child_physical} />
        </div>
      </DocSection>

      {/* 2. Disability profile */}
      <DocSection num="02" title="Disability & communication profile">
        <h3>Diagnoses</h3>
        <ChipsSelectedOnly
          options={[
            'Autism Spectrum Disorder',
            'non-speaking or Minimally Verbal',
            'Intellectual / Developmental Disability',
            'Sensory Processing Disorder',
            'Anxiety Disorder',
            'ADHD',
            'Seizure Disorder',
          ]}
          selected={d.dx}
        />
        {d.dx_other && <div className="doc-paragraph"><strong>Other:</strong> {d.dx_other}</div>}

        <h3 style={{marginTop: 14}}>How my child communicates</h3>
        <ChipsSelectedOnly
          options={[
            'Does not use spoken words',
            'Uses picture cards',
            'Points or gestures',
            'Uses written words',
          ]}
          selected={d.comm}
        />
        <div style={{marginTop: 6}}>
          {d.comm_words && <Row k="Uses some words" v={d.comm_words} />}
          {d.comm_sign && <Row k="Sign language" v={d.comm_sign} />}
          {d.comm_aac && <Row k="AAC / device" v={d.comm_aac} />}
          {d.comm_other && <Row k="Other method" v={d.comm_other} />}
          {d.understand && <Row k="Understands" v={d.understand} />}
          {d.uses && <Row k="Uses" v={d.uses} />}
        </div>

        <h3 style={{marginTop: 14}}>How to communicate with my child</h3>
        <ChipsSelectedOnly
          options={[
            'Use simple, short sentences',
            'Use visual aids or pictures',
            'Avoid loud voices or sudden movements',
          ]}
          selected={d.comm_how}
        />
        <div style={{marginTop: 6}}>
          {d.comm_time && <Row k="Processing time" v={`${d.comm_time} seconds`} />}
          {d.comm_notes && <Row k="Other notes" v={d.comm_notes} />}
        </div>
      </DocSection>

      {/* 3. Stress */}
      <DocSection num="03" title="Stress responses during emergencies">
        <div className="doc-two-col">
          <div>
            <h3>Running / elopement</h3>
            <ChipsSelectedOnly
              options={[
                'Runs toward doors, exits, or open spaces',
                'Bolts without warning when startled',
                'Attracted to water — check water first',
                'Does not understand traffic danger',
                'Does not respond to their name when running',
              ]}
              selected={d.run}
            />

            <h3 style={{marginTop: 12}}>Shutdown / withdrawal</h3>
            <ChipsSelectedOnly
              options={[
                'Becomes completely still and unresponsive',
                'Stops making eye contact',
                'Covers ears or eyes',
                'Goes non-speaking even if usually verbal',
                'Cannot follow instructions when overwhelmed',
              ]}
              selected={d.shutdown}
            />
          </div>
          <div>
            <h3>Meltdown / distress</h3>
            <ChipsSelectedOnly
              options={[
                'Screams or cries',
                'Drops to ground and refuses to move',
                'Becomes physically reactive (hitting, kicking)',
              ]}
              selected={d.meltdown}
            />
            {d.self_injurious && <div className="doc-paragraph"><strong>Self-injurious behavior:</strong> {d.self_injurious}</div>}

            <h3 style={{marginTop: 12}}>Sensory triggers</h3>
            <ChipsSelectedOnly
              options={[
                'Loud noises — sirens, shouting, alarms',
                'Bright or flashing lights',
                'Being touched by strangers',
                'Crowded or chaotic environments',
              ]}
              selected={d.sensory}
            />
            {d.sensory_other && <div className="doc-paragraph"><strong>Other triggers:</strong> {d.sensory_other}</div>}
          </div>
        </div>

        <div className="doc-quote" style={{marginTop: 10}}>
          My child does <strong>not</strong> understand commands like &ldquo;Stop,&rdquo; &ldquo;Freeze,&rdquo;
          or &ldquo;Hands up.&rdquo; Non-compliance is not defiance — it is disability.
        </div>
      </DocSection>

      {/* 4. Calm */}
      <DocSection num="04" title="What helps my child calm down">
        <div className="doc-two-col">
          <div>
            <h3>Comfort objects</h3>
            {d.comfort_toy && <Row k="Favorite toy" v={d.comfort_toy} />}
            <ChipsSelectedOnly
              options={['Weighted blanket or vest', 'Noise-canceling headphones']}
              selected={d.comfort_basic}
            />
            {d.comfort_fidget && <Row k="Fidget toys" v={d.comfort_fidget} />}
            {d.comfort_device && <Row k="Tablet / apps" v={d.comfort_device} />}
            {d.comfort_other && <Row k="Other" v={d.comfort_other} />}

            <h3 style={{marginTop: 12}}>Calming strategies</h3>
            <ChipsSelectedOnly
              options={[
                'Deep pressure — firm hugs, weighted items',
                'Rocking or rhythmic movement',
                'Quiet, dimly lit space',
                'Squeezing hands together or pressing palms hard',
                'Pressing feet flat into the floor',
                'Humming one note',
                'Holding something textured or smooth',
                'Smelling something familiar',
                'Looking at one still object',
              ]}
              selected={d.calm_strategies}
            />
            {d.calm_songs && <div className="doc-paragraph"><strong>Songs:</strong> {d.calm_songs}</div>}
            {d.calm_other && <div className="doc-paragraph"><strong>Other:</strong> {d.calm_other}</div>}
          </div>

          <div>
            <h3>Do NOT do the following</h3>
            <ChipsSelectedOnly
              options={[
                'Do not grab or restrain suddenly',
                'Do not raise your voice or yell',
                'Do not force eye contact',
                'Do not crowd or surround my child',
                'Do not separate from trusted caregiver',
                'Do not touch without giving a warning first',
              ]}
              selected={d.dont}
            />
            {d.dont_other && <div className="doc-paragraph"><strong>Other triggers to avoid:</strong> {d.dont_other}</div>}
          </div>
        </div>
      </DocSection>

      {/* 5. Medical */}
      <DocSection num="05" title="Medical information">
        <div className="doc-two-col">
          <div>
            <h3>Medication #1 {d.med1_critical && <span style={{color:'#8E4325'}}>• Critical</span>}</h3>
            <Row k="Name" v={d.med1_name} />
            <Row k="Dosage" v={d.med1_dose} />
            {d.med1_miss && <Row k="If missed" v={d.med1_miss} />}

            <h3 style={{marginTop: 12}}>Medication #2 {d.med2_critical && <span style={{color:'#8E4325'}}>• Critical</span>}</h3>
            <Row k="Name" v={d.med2_name} />
            <Row k="Dosage" v={d.med2_dose} />
            {d.med2_miss && <Row k="If missed" v={d.med2_miss} />}
          </div>
          <div>
            <h3>Allergies</h3>
            <Row k="Food" v={d.allergy_food} />
            <Row k="Medication" v={d.allergy_med} />

            <h3 style={{marginTop: 12}}>Conditions</h3>
            {(d.seizure_type || d.seizure_last || d.seizure_do) && (
              <>
                <Row k="Seizure type" v={d.seizure_type} />
                <Row k="Last seizure" v={d.seizure_last} />
                {d.seizure_do && <Row k="During seizure" v={d.seizure_do} />}
              </>
            )}
            {d.diabetes && <div className="doc-paragraph">✓ Diabetes — insulin dependent</div>}
            {d.asthma && <div className="doc-paragraph">✓ Asthma — uses inhaler</div>}
            {d.condition_other && <Row k="Other" v={d.condition_other} />}
          </div>
        </div>

        <h3 style={{marginTop: 12}}>Medical equipment</h3>
        <ChipsSelectedOnly
          options={['Wheelchair', 'Walker', 'Hearing aids', 'Glasses', 'EpiPen']}
          selected={d.equipment}
        />
        {d.equipment_other && <div className="doc-paragraph"><strong>Other:</strong> {d.equipment_other}</div>}
      </DocSection>

      {/* 6. Caregivers */}
      <DocSection num="06" title="Trusted caregivers & emergency contacts">
        <div className="doc-two-col">
          <div>
            <h3>Primary caregiver</h3>
            <Row k="Name" v={d.c1_name} />
            <Row k="Relationship" v={d.c1_rel} />
            <Row k="Phone" v={d.c1_phone} />
            <Row k="Languages" v={d.c1_lang} />
            <Row k="Address" v={d.c1_addr} />

            <h3 style={{marginTop: 12}}>Secondary caregiver</h3>
            <Row k="Name" v={d.c2_name} />
            <Row k="Relationship" v={d.c2_rel} />
            <Row k="Phone" v={d.c2_phone} />
            <Row k="Languages" v={d.c2_lang} />
            <Row k="Address" v={d.c2_addr} />
          </div>
          <div>
            <h3>If caregiver is detained, child should go to</h3>
            <Row k="Name" v={d.det_name} />
            <Row k="Relationship" v={d.det_rel} />
            <Row k="Phone" v={d.det_phone} />
            <Row k="Address" v={d.det_addr} />
            {d.det_legal && <div className="doc-paragraph">✓ Legally authorized (notarized letter attached)</div>}

            <h3 style={{marginTop: 12}}>Backup emergency contact</h3>
            <Row k="Name" v={d.bk_name} />
            <Row k="Relationship" v={d.bk_rel} />
            <Row k="Phone" v={d.bk_phone} />
            <Row k="Languages" v={d.bk_lang} />
            <Row k="Address" v={d.bk_addr} />
          </div>
        </div>

        <h3 style={{marginTop: 12}}>Providers</h3>
        <div className="doc-two-col">
          <Row k="Doctor" v={d.doctor} />
          <Row k="Therapist / case manager" v={d.therapist} />
        </div>
      </DocSection>

      {/* 7. ID */}
      <DocSection num="07" title="Identification my child carries">
        <ChipsSelectedOnly
          options={[
            'ID bracelet or necklace with contact info and disability note',
            'Laminated card in pocket with emergency info',
            'Medical alert bracelet',
          ]}
          selected={d.id_carries}
        />
        <div style={{marginTop: 6}}>
          {d.gps_type && <Row k="GPS device" v={d.gps_type} />}
          {d.gps_phone && <Row k="GPS phone" v={d.gps_phone} />}
          {d.id_location && <Row k="Where to find ID" v={d.id_location} />}
        </div>
      </DocSection>

      {/* 8. Separation */}
      <DocSection num="08" title="If my child is separated">
        <div className="doc-paragraph">
          <strong>Call 911 immediately</strong> if child is missing or separated. Also call the
          National Center for Missing &amp; Exploited Children: <strong>1-800-843-5678</strong>.
          Activate any GPS tracker and contact your immigration attorney.
        </div>

        <h3>Places to check first</h3>
        <ChipsSelectedOnly
          options={[
            'Water — pools, ponds, rivers, fountains — CHECK FIRST',
            'Playgrounds',
            'Small enclosed spaces — closets, under beds, in cabinets',
          ]}
          selected={d.sep_places}
        />
        {d.sep_stores && <Row k="Specific places" v={d.sep_stores} />}
        {d.sep_other && <Row k="Other places" v={d.sep_other} />}
        {d.sep_responds && <Row k="My child responds to" v={d.sep_responds} />}

        <div className="doc-paragraph" style={{marginTop: 8, fontSize: '9.5pt', color: '#555'}}>
          <strong>Search tips:</strong> Look in small, enclosed spaces. Do not expect a response to
          their name. Use a favorite toy or food to get attention. Approach slowly and calmly.
        </div>
      </DocSection>

      {/* 9. Officers */}
      <DocSection num="09" title="Instructions for ICE officers">
        <div className="doc-quote">
          &ldquo;My child has a disability. They cannot understand your commands. They need me to
          stay with them. Separating us will cause extreme distress and may result in self-injury.
          They have the right to disability accommodations under federal law.&rdquo;
        </div>
        <h3>Requested accommodations</h3>
        <ul style={{margin: '4px 0 6px 18px', padding: 0, fontSize: '10pt', lineHeight: 1.5}}>
          <li>Allow parent / trusted caregiver to stay with child at all times</li>
          <li>Give extra time for the child to process what is happening</li>
          <li>Use a calm voice and slow movements</li>
          <li>Avoid physical restraint — causes severe distress</li>
          <li>Allow comfort objects (toy, device, blanket)</li>
          <li>Do not separate child from caregivers during transport or detention</li>
        </ul>
      </DocSection>

      {/* 10. Legal */}
      <DocSection num="10" title="Legal rights">
        <div className="doc-paragraph">
          Under the <strong>Americans with Disabilities Act (ADA)</strong> and <strong>Section 504, Rehabilitation Act of 1973</strong>,
          this child has the right to: reasonable accommodations during encounters; remaining with
          their parent or caregiver; continued access to medications and medical care; having
          disability-related behaviors understood, not punished; and communicating in their
          preferred method.
        </div>
        <h3>If rights are violated</h3>
        <div className="doc-two-col">
          <Row k="ICE Office of Civil Rights" v="(202) 401-1474" />
          <Row k="Disability Rights Education & Defense Fund" v="(510) 644-2555" />
        </div>
        <div className="doc-paragraph" style={{fontSize: '9.5pt'}}>
          Document everything — dates, times, names, what happened. Request denial of
          accommodations in writing. Contact your immigration attorney immediately.
        </div>
      </DocSection>

      {/* 11. Emergency Preparedness Kit — static reference list */}
      <DocSection num="11" title="Emergency preparedness kit">
        <div className="doc-paragraph" style={{marginBottom: 8}}>
          <strong>Assemble this kit now and keep it ready.</strong>
        </div>
        <div className="doc-two-col">
          <div>
            <h3>Documents (in waterproof bag)</h3>
            <ul style={{margin:'2px 0 8px 16px', padding:0, fontSize:'9.5pt', lineHeight:1.45}}>
              <li>This completed safety plan — multiple copies</li>
              <li>Child&rsquo;s birth certificate (copy)</li>
              <li>Medical records and diagnosis documentation</li>
              <li>Current prescriptions list</li>
              <li>Recent photos — multiple angles</li>
              <li>Notarized letter authorizing alternate caregiver</li>
              <li>Immigration attorney contact information</li>
              <li>Health insurance cards</li>
            </ul>

            <h3 style={{marginTop: 10}}>Comfort &amp; communication items</h3>
            <ul style={{margin:'2px 0 8px 16px', padding:0, fontSize:'9.5pt', lineHeight:1.45}}>
              <li>Favorite toy or comfort object</li>
              <li>Communication device (charged) or picture cards</li>
              <li>Noise-canceling headphones</li>
              <li>Weighted lap pad or small blanket</li>
              <li>Fidget toys</li>
              <li>Tablet with calming apps / videos (charged + charger)</li>
            </ul>
          </div>
          <div>
            <h3>Medical supplies (2-week supply minimum)</h3>
            <ul style={{margin:'2px 0 8px 16px', padding:0, fontSize:'9.5pt', lineHeight:1.45}}>
              <li>All medications in original bottles</li>
              <li>Medical equipment</li>
              <li>EpiPen or emergency medications</li>
              <li>First aid kit</li>
            </ul>

            <h3 style={{marginTop: 10}}>Basic needs</h3>
            <ul style={{margin:'2px 0 8px 16px', padding:0, fontSize:'9.5pt', lineHeight:1.45}}>
              <li>Safe foods child will eat (non-perishable)</li>
              <li>Preferred drinking cup or bottle</li>
              <li>Diapers or pull-ups if needed</li>
              <li>Two changes of clothes</li>
              <li>Familiar blanket or pillow</li>
            </ul>
          </div>
        </div>
      </DocSection>

      {/* 12. Additional */}
      <DocSection num="12" title="Additional information">
        {d.extra_things && <Row k="Other important info" v={d.extra_things} />}
        {d.strengths && <Row k="Strengths & interests" v={d.strengths} />}
        {d.most_calm && <Row k="Most calm when" v={d.most_calm} />}
      </DocSection>

      {/* Signature */}
      <div className="doc-signature">
        <div className="doc-sig-block">
          <div className="line">
            <div className="line-text">{d.sig_name || ''}</div>
          </div>
          <div className="sig-label">Parent / Caregiver — printed name</div>
        </div>
        <div className="doc-sig-block">
          <div className="line">
            <div className="line-text">{d.sig_rel || ''}</div>
          </div>
          <div className="sig-label">Relationship to child</div>
        </div>
        <div className="doc-sig-block">
          <div className="line">
            <div className="line-text">{d.sig_date || ''}</div>
          </div>
          <div className="sig-label">Date completed</div>
        </div>
      </div>

      <div className="doc-footer">
        <div>
          Update this plan every 6 months or when information changes.
          {d.sig_next && <> Next review: <strong>{d.sig_next}</strong>.</>}
        </div>
        <div>This document is not legal advice.</div>
      </div>
    </div>
  );
}

window.PrintableDocument = PrintableDocument;
