<context>
// components/LegalText.js

import React, { useContext, useState, useRef } from 'react';
import {
  ScrollView,
  Text,
  StyleSheet,
  View,
  TextInput,
  TouchableOpacity,
  Modal,
} from 'react-native';
import Checkbox from 'expo-checkbox';
import { MediaContext } from '../context/MediaContext';
import SignatureScreen from 'react-native-signature-canvas';

const LegalText = () => {
  const { media, updateLegalText } = useContext(MediaContext);
  const { checkboxes, textInputs, signatures, dates } = media.legalText;

  const [signatureModalVisible, setSignatureModalVisible] = useState(false);
  const [currentSignaturePerson, setCurrentSignaturePerson] = useState(null);

  const signatureRef = useRef(null);

  const toggleCheckbox = (item) => {
    updateLegalText({
      checkboxes: {
        ...checkboxes,
        [item]: !checkboxes[item],
      },
    });
  };

  const setTextInput = (field, value) => {
    updateLegalText({
      textInputs: {
        ...textInputs,
        [field]: value,
      },
    });
  };

  const handleSignature = (signature) => {
    updateLegalText({
      signatures: {
        ...signatures,
        [currentSignaturePerson]: signature,
      },
      dates: {
        ...dates,
        [currentSignaturePerson]: new Date().toISOString().split('T')[0],
      },
    });
    setSignatureModalVisible(false);
  };

  const openSignaturePad = (person) => {
    setCurrentSignaturePerson(person);
    setSignatureModalVisible(true);
  };

  const SignatureField = ({ person, label }) => (
    <View style={styles.signatureField}>
      <Text style={styles.label}>{label}</Text>
      <TouchableOpacity
        style={styles.signatureBox}
        onPress={() => openSignaturePad(person)}
      >
        {signatures[person] ? (
          <Text style={styles.signaturePlaceholder}>Signature captured</Text>
        ) : (
          <Text style={styles.signaturePlaceholder}>Tap to sign</Text>
        )}
      </TouchableOpacity>
      <Text style={styles.dateText}>Date: {dates[person] || 'Not signed'}</Text>
    </View>
  );

  const handleClear = () => {
    signatureRef.current.clearSignature();
  };

  const handleSave = () => {
    signatureRef.current.readSignature();
  };

  return (
    <ScrollView style={styles.container}>
      <Text style={styles.title}>Consent Agreement</Text>
      
      <Text style={styles.disclaimer}>
        Disclaimer: This form is intended to facilitate open communication and mutual understanding between consenting adults engaging in sexual activities. It is not a legally binding document and should not replace ongoing verbal consent. Please consult a legal professional to understand the legal standing of such agreements in your jurisdiction.
      </Text>

      <Text style={styles.sectionTitle}>Introduction</Text>
      <Text style={styles.paragraph}>
        This agreement is entered into by the undersigned parties to clearly communicate mutual understanding and consent regarding specific sexual activities. The purpose of this agreement is to foster respect, open communication, and a safe, consensual environment for all involved.
      </Text>

      <Text style={styles.sectionTitle}>Parties Involved</Text>
      
      <Text style={styles.label}>Person 1:</Text>
      <TextInput
        style={styles.input}
        placeholder="Name"
        value={textInputs.person1Name}
        onChangeText={(text) => setTextInput('person1Name', text)}
      />
      <TextInput
        style={styles.input}
        placeholder="Age"
        value={textInputs.person1Age}
        onChangeText={(text) => setTextInput('person1Age', text)}
      />
      <TextInput
        style={styles.input}
        placeholder="Contact Information"
        value={textInputs.person1Contact}
        onChangeText={(text) => setTextInput('person1Contact', text)}
      />
      <View style={styles.checkboxContainer}>
        <Checkbox
          value={checkboxes.person1IdVerified}
          onValueChange={() => toggleCheckbox('person1IdVerified')}
          color={checkboxes.person1IdVerified ? '#4630EB' : undefined}
        />
        <Text style={styles.label}>Identification Verified</Text>
      </View>

      <Text style={styles.label}>Person 2:</Text>
      <TextInput
        style={styles.input}
        placeholder="Name"
        value={textInputs.person2Name}
        onChangeText={(text) => setTextInput('person2Name', text)}
      />
      <TextInput
        style={styles.input}
        placeholder="Age"
        value={textInputs.person2Age}
        onChangeText={(text) => setTextInput('person2Age', text)}
      />
      <TextInput
        style={styles.input}
        placeholder="Contact Information"
        value={textInputs.person2Contact}
        onChangeText={(text) => setTextInput('person2Contact', text)}
      />
      <View style={styles.checkboxContainer}>
        <Checkbox
          value={checkboxes.person2IdVerified}
          onValueChange={() => toggleCheckbox('person2IdVerified')}
          color={checkboxes.person2IdVerified ? '#4630EB' : undefined}
        />
        <Text style={styles.label}>Identification Verified</Text>
      </View>

      <Text style={styles.paragraph}>
        If more than two parties are involved, please attach additional pages with their information.
      </Text>

      <Text style={styles.sectionTitle}>Acknowledgments</Text>
      <Text style={styles.paragraph}>
        By signing this agreement, both parties acknowledge that they:
      </Text>
      <Text style={styles.bulletPoint}>
        • Are above the legal age of consent in the jurisdiction where this agreement is being made and have verified each other's identification.
      </Text>
      <Text style={styles.bulletPoint}>
        • Are fully aware of and understand the nature of the sexual activities being discussed.
      </Text>
      <Text style={styles.bulletPoint}>
        • Are entering into this agreement voluntarily, without coercion, pressure, or undue influence.
      </Text>
      <Text style={styles.bulletPoint}>
        • Have the mental and emotional capacity to make informed decisions.
      </Text>
      <Text style={styles.bulletPoint}>
        • Are not under the influence of drugs or alcohol that could impair their judgment at the time of signing.
      </Text>
      <Text style={styles.bulletPoint}>
        • Understand that consent is a continuous process and can be withdrawn at any point before or during the sexual activity.
      </Text>
      <Text style={styles.bulletPoint}>
        • Recognize that this agreement does not waive the right to withdraw consent at any time.
      </Text>

      <Text style={styles.sectionTitle}>Consent to Specific Activities</Text>
      <Text style={styles.paragraph}>Both parties agree to engage in the following activities (check all that apply):</Text>

      <View style={styles.checkboxContainer}>
        <Checkbox
          value={checkboxes.kissing}
          onValueChange={() => toggleCheckbox('kissing')}
          color={checkboxes.kissing ? '#4630EB' : undefined}
        />
        <Text style={styles.label}>Kissing</Text>
      </View>

      <View style={styles.checkboxContainer}>
        <Checkbox
          value={checkboxes.sexualTouching}
          onValueChange={() => toggleCheckbox('sexualTouching')}
          color={checkboxes.sexualTouching ? '#4630EB' : undefined}
        />
        <Text style={styles.label}>Sexual touching (manual stimulation)</Text>
      </View>

      <View style={styles.checkboxContainer}>
        <Checkbox
          value={checkboxes.oralSex}
          onValueChange={() => toggleCheckbox('oralSex')}
          color={checkboxes.oralSex ? '#4630EB' : undefined}
        />
        <Text style={styles.label}>Oral sex</Text>
      </View>

      <View style={styles.checkboxContainer}>
        <Checkbox
          value={checkboxes.vaginalIntercourse}
          onValueChange={() => toggleCheckbox('vaginalIntercourse')}
          color={checkboxes.vaginalIntercourse ? '#4630EB' : undefined}
        />
        <Text style={styles.label}>Vaginal intercourse</Text>
      </View>

      <View style={styles.checkboxContainer}>
        <Checkbox
          value={checkboxes.analIntercourse}
          onValueChange={() => toggleCheckbox('analIntercourse')}
          color={checkboxes.analIntercourse ? '#4630EB' : undefined}
        />
        <Text style={styles.label}>Anal intercourse</Text>
      </View>

      <View style={styles.checkboxContainer}>
        <Checkbox
          value={checkboxes.useOfSexualDevices}
          onValueChange={() => toggleCheckbox('useOfSexualDevices')}
          color={checkboxes.useOfSexualDevices ? '#4630EB' : undefined}
        />
        <Text style={styles.label}>Use of sexual devices</Text>
      </View>

      <TextInput
        style={styles.input}
        placeholder="Specify sexual devices"
        value={textInputs.sexualDevicesSpecify}
        onChangeText={(text) => setTextInput('sexualDevicesSpecify', text)}
      />

      <View style={styles.checkboxContainer}>
        <Checkbox
          value={checkboxes.other}
          onValueChange={() => toggleCheckbox('other')}
          color={checkboxes.other ? '#4630EB' : undefined}
        />
        <Text style={styles.label}>Other</Text>
      </View>

      <TextInput
        style={styles.input}
        placeholder="Specify other activities"
        value={textInputs.otherActivitiesSpecify}
        onChangeText={(text) => setTextInput('otherActivitiesSpecify', text)}
      />

      <Text style={styles.sectionTitle}>Definitions</Text>
      <Text style={styles.paragraph}>
        Kissing: Oral contact with another person's lips or body.{'\n'}
        Sexual touching: Physical contact with another person's intimate areas (e.g., genitals, buttocks, breasts) for sexual arousal or gratification.{'\n'}
        Oral sex: Oral stimulation of another person's genitalia.{'\n'}
        Vaginal intercourse: Penetration of the vagina by the penis or a sexual device.{'\n'}
        Anal intercourse: Penetration of the anus by the penis, fingers, or a sexual device.{'\n'}
        Use of sexual devices: Incorporation of sex toys or props into sexual activities as specified.{'\n'}
        Other: Any additional activities specified by the participants.
      </Text>

      <Text style={styles.sectionTitle}>Terms and Conditions</Text>

      <Text style={styles.label}>Continuous Consent:</Text>
      <Text style={styles.paragraph}>
        Both parties understand that consent is an ongoing process and can be withdrawn at any time before or during the sexual activity.{'\n'}
        Any indication of withdrawal of consent, whether verbal or non-verbal, must be respected immediately, and all activities must cease.
      </Text>

      <Text style={styles.label}>Communication:</Text>
      <Text style={styles.paragraph}>
        Both parties agree to communicate openly and respectfully about boundaries, comfort levels, and any changes in consent during the activity.{'\n'}
        Safe words or signals will be used to ensure clear communication.
      </Text>

      <Text style={styles.label}>Safe Word/Signal:</Text>
      <TextInput
        style={styles.input}
        placeholder="Enter safe word or signal"
        value={textInputs.safeWordSignal}
        onChangeText={(text) => setTextInput('safeWordSignal', text)}
      />
      <Text style={styles.paragraph}>
        This word or signal will be used to indicate an immediate halt to all activities.
      </Text>

      <Text style={styles.label}>Contraception and Protection:</Text>
      <TextInput
        style={styles.input}
        placeholder="Specify contraception methods"
        value={textInputs.contraceptionMethods}
        onChangeText={(text) => setTextInput('contraceptionMethods', text)}
      />
      <Text style={styles.paragraph}>
        Both parties commit to discussing any changes in contraception or protection methods.
      </Text>

      <Text style={styles.label}>Sexually Transmitted Infections (STIs):</Text>
      <Text style={styles.paragraph}>
        Both parties confirm that they have disclosed any known STIs to each other.{'\n'}
        Both parties agree to inform the other if they become aware of any changes to their STI status.
      </Text>

      <Text style={styles.label}>Recent STI Testing:</Text>
      <TextInput
        style={styles.input}
        placeholder="Person 1 Last Tested On"
        value={textInputs.person1LastTested}
        onChangeText={(text) => setTextInput('person1LastTested', text)}
      />
      <TextInput
        style={styles.input}
        placeholder="Person 2 Last Tested On"
        value={textInputs.person2LastTested}
        onChangeText={(text) => setTextInput('person2LastTested', text)}
      />

      <Text style={styles.label}>Health and Safety Plan:</Text>
      <TextInput
        style={styles.input}
        placeholder="Specify health and safety plan"
        value={textInputs.healthSafetyPlan}
        onChangeText={(text) => setTextInput('healthSafetyPlan', text)}
      />

      <Text style={styles.label}>Limits and Boundaries:</Text>
      <Text style={styles.paragraph}>
        Both parties have discussed and agreed upon personal limits and hard boundaries.
      </Text>
      <TextInput
        style={styles.input}
        placeholder="Specify activities or areas to avoid"
        value={textInputs.activitiesToAvoid}
        onChangeText={(text) => setTextInput('activitiesToAvoid', text)}
      />

      <Text style={styles.label}>Aftercare:</Text>
      <Text style={styles.paragraph}>
        The parties agree to provide appropriate aftercare following the activities, addressing emotional and physical well-being.
      </Text>
      <TextInput
        style={styles.input}
        placeholder="Specify aftercare preferences"
        value={textInputs.aftercarePreferences}
        onChangeText={(text) => setTextInput('aftercarePreferences', text)}
      />

      <Text style={styles.label}>Privacy and Confidentiality:</Text>
      <Text style={styles.paragraph}>
        Both parties agree to keep the details of this agreement and the activities confidential unless required by law to disclose.
      </Text>

      <Text style={styles.label}>Storage of Agreement:</Text>
      <Text style={styles.paragraph}>
        The agreement will be stored in a secure location accessible to both parties.
      </Text>

      <Text style={styles.sectionTitle}>Signatures</Text>
      <Text style={styles.paragraph}>
        By signing this form, both parties affirm that they have read and fully understand this agreement, and that all information provided is accurate and truthful. They also acknowledge that this agreement does not replace the need for ongoing, enthusiastic consent.
      </Text>

      <SignatureField person="person1" label="Person 1:" />
      <SignatureField person="person2" label="Person 2:" />
      <SignatureField person="witness" label="Witness (Optional):" />

      <TextInput
        style={styles.input}
        placeholder="Witness Name (Print)"
        value={textInputs.witnessName}
        onChangeText={(text) => setTextInput('witnessName', text)}
      />

      {/* Signature Modal */}
      <Modal
        visible={signatureModalVisible}
        transparent={true}
        animationType="slide"
      >
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <SignatureScreen
              ref={signatureRef}
              onOK={handleSignature}
              onEmpty={() => console.log("No signature")}
              descriptionText="Sign here"
              webStyle={`
                .m-signature-pad--footer {
                  display: none;
                }
                body,html {
                  height: 100%;
                  width: 100%;
                  margin: 0;
                  padding: 0;
                }
              `}
            />
            <View style={styles.buttonContainer}>
              <TouchableOpacity
                style={styles.button}
                onPress={handleClear}
              >
                <Text style={styles.buttonText}>Clear</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.button}
                onPress={handleSave}
              >
                <Text style={styles.buttonText}>Save</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.button, styles.cancelButton]}
                onPress={() => setSignatureModalVisible(false)}
              >
                <Text style={styles.buttonText}>Cancel</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
    textAlign: 'center',
  },
  disclaimer: {
    fontSize: 12,
    fontStyle: 'italic',
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginTop: 20,
    marginBottom: 10,
  },
  paragraph: {
    fontSize: 14,
    marginBottom: 10,
    lineHeight: 20,
  },
  label: {
    fontSize: 16,
    marginBottom: 5,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    padding: 10,
    marginBottom: 15,
  },
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  bulletPoint: {
    fontSize: 14,
    marginBottom: 5,
    paddingLeft: 15,
  },
  signatureField: {
    marginBottom: 20,
  },
  signatureBox: {
    height: 60,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    justifyContent: 'center',
    alignItems: 'center',
  },
  signaturePlaceholder: {
    color: '#999',
  },
  dateText: {
    marginTop: 5,
    fontSize: 12,
    color: '#666',
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalContent: {
    backgroundColor: 'white',
    borderRadius: 10,
    padding: 10,
    width: '90%',
    height: 500, // Adjust height as needed
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 10,
  },
  button: {
    backgroundColor: '#4630EB',
    padding: 10,
    borderRadius: 5,
    flex: 1,
    marginHorizontal: 5,
    alignItems: 'center',
  },
  cancelButton: {
    backgroundColor: '#f44336', // Red color for cancel
  },
  buttonText: {
    color: '#FFF',
    fontWeight: 'bold',
  },
});

export default LegalText;
</context>
<instruction>
keep the layout the same, but make it so the user can click on the text beside the checkbox and it will also check the box
</instruction>