/** @jsxImportSource @emotion/react */
import 'twin.macro';

import React, { FunctionComponent } from 'react';

export const AccordionContext = React.createContext<string | null>(null);

export const AccordionGroup: FunctionComponent = (props) => {
  const [ref, setRef] = React.useState(null);
  const [activeButtonId, setActiveButtonId] = React.useState<string>(null);

  React.useEffect(() => {
    if (!ref) return;
    const handler = (e: CustomEvent<string>) => {
      setActiveButtonId(e.detail);
    };
    ref.addEventListener('accordion', handler);
    return () => {
      ref.removeEventListener('accordion', handler);
    };
  }, [ref]);

  return (
    <AccordionContext.Provider value={activeButtonId}>
      <div ref={setRef} {...props} />
    </AccordionContext.Provider>
  );
};

export default AccordionGroup;
